开发者

jQuery live() function

I have a problem with the jQuery's live() function.

I'm creating the shopping basket with PHP and make a json call to the php script to add specific item to the basket. Rather than re-binding the click to the button ( tag) I've decided to use live(), however it doesn't seem to like it.

Here's my call:

if ($('.add_to_basket').length > 0) {
    $('.add_to_basket').live('click', function() {
        var button = $(this);
        var id = $(this).attr("rel");
        $.getJSON("/basket/action/add/id/" + id, function(data) {
            if (!data.error) {
                $('.basket_no_of_items').text(data.no_of_items);
                $('.basket_items_total').text(data.total);
                button.text('Remove from the basket');
            }           
        });
        return false;
    });
}

Any idea what I might be doing wrong?

I've checked with firebug and it seem to post the request to only /basket/action/add - with开发者_StackOverflow社区out id bit.


The whole idea of using live() is to register a function on the occurrence of an event (eg. click) on a set of elements whether they exist or not at the time of creation of the function.

Adding ($('.add_to_basket').length > 0) will check whether this particular set of elements exist or not. This is counter productive as per my description above. So, either:

  1. Remove ($('.add_to_basket').length > 0) and this should work for all .add_to_basket elements
  2. Change $('.add_to_basket').live('click', function() {...}); to $('.add_to_basket').click(function() {...}); and wrap it around with a $(document).ready() to ensure that all DOM elements have loaded when the function is registered to the click.

Hope this makes sense.

Sumit


Try removing the "length" check, I bet it's interfering with the .live() function.


change $.getJSON("/basket/action/add/id/" + id, function(data) {}) to $.getJSON("/basket/action/add/id/" ,{ pid : id}, function(data) {})

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜