开发者

usage of jquery .live() to work with both present and future DOM

I've my jQuery code as

$('#tarea').click(function() {
     // Do stuffs
});

This works fine for the button #tarea loaded along with this script. If the button #tarea had been loaded using ajax in future, than the above code doesn't work.

Now I changed the code to

$('#tarea').live('click', function() {
     // Do stuffs
});

This time, the button #tarea if loaded along with the script doesn't work. But the script works with the button if 开发者_JAVA百科generated using ajax.

How do I write the script so that in both cases, it works??


.live() works in both cases without doing anything additional to what you have already done. I would check for some other problems in your code that might be preventing this from happening.

Important: One thing to check is to make sure that your .live() event is being bound and that it doesn't rely on some other event happening. It might help to post the important parts of you JavaScript file. Personally I like to declare my .live() events globally.

I do something like this:

// this is what I mean by global because it is outside the document.ready
$("#test").live("click", function() {
    // do stuff
});

$(function() {
    // do stuff when document is ready
});

If you want to prove what I said above, you only need to put the button and the .live() JavaScript code in a new HTML file.


You put :

$('#tarea').click(function() {
     // Do stuffs
});

in a function.

And when you load via ajax, you add a callback function (the one above) in second parameter of .load()

For example :

.load(target_url, function() { $('#tarea').click(function() { blablabla; }})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜