开发者

jquery function to the element that is being appended?

I'm trying to append some html stuff, and I was wondering how come when I try to write some jquery function, that element that was just ap开发者_开发技巧pended won't work?

For instance, if I had a list of text and when you click on something, that list will populate with some sort of .append('more text') to that list. Then if I have written some jquery function saying when hovering over that text, it won't work. It will only work on text that was already populated before the append.

I hope my example clarifies my question?

Thanks for your help!


use jQuery's live() method instead of the regular event handler. For example:

$('#myelement > *').live('mouseenter', function(evt) {
    $(this).addClass('hovered');
}).live('mouseleave', function(evt) {
    $(this).removeClass('hovered');
})

now, when you do this

$('#myelement').append( '<div>More Stuff</div>' );

the newly added div will get the mouseenter and mouseleave events as you wanted.


You are probably binding your handlers using .click(), .hover(), etc. These only work for items already on the page at the time the handler is bound.

Try using .live(event, handler) instead. This binds to elements which match now, and any elements that match that are added later.

e.g.

$('li').live('click', function() {
    // do stuff here
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜