开发者

.live not working after ajax $.post

I am trying to use .live to ensure that my elements respond to click events even after an ajax call (in my case i use $.post) so for example after my ajax call i do this:

$('.link').live({
    click: function() {
        alert('testing');
    }
});

it doesn't working. Only if i switch it to using a normal click event like this:

$('.link').click(function() {
    alert('testing);
}

it works. But the thing is the $link only appears to the user only after each ajax call and is the one actually making the开发者_开发知识库 ajax call. So if i use a normal click event, it will only work once after the first ajax call (i bind the event after the first ajax call) which shows the $link for the first time.

After the $link is shown for the first time, and is clicked by the user for the first time, it will show a list of items including the $link again at the bottom. However, this time it doesn't work anymore because i am still only binding the click event without using .live.

How do i make it so that .live works, which will enable the link to work everytime after N number of times of clicks?

Edited: Change $list to using a selector. Sorry about the unclear information before. I am in fact using a selector for using .live . I am actually trying to provide a 'View more' functionality. So after a user enters something in a textbox, the search results appear (via ajax) and the 'View more' link appears at the bottom. When the user clicks it, more relevant search results will be appended to the list and another 'View more' link will be at the bottom of the list again. However, this time it doesn't work anymore because i can't get the .live to work with it.


You can try it like I always do it like:

$(".class").live("click", function () {
    //Do something
});


You use a selector when you specify the live delegate. Example:

$('.SomeClass').live(...

This will bind the event to the document, where it will check the origin of the event. If the origin matches the selector, the event handler is triggered.

You have to use a selector when you bind the live delegate, you can't use any other method of traversing the DOM to find the elements, as the selector is evaluated when the event happens, not when the delegate is bound.


I solved the problem using event bubbling instead. What i did was instead of using .live(), i did this:

$('.linkParent').click(function(event) {

    $tgt = $(event.target);

    if ($tgt.attr('class')=='link') { alert('works now!'); }

});

Such that $('.link') is always inside $('.linkParent') and the ajax call is always only loading stuff inside of $('.linkParent').

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜