开发者

Jquery bind doesnt work on AJAX loaded HTML

开发者 https://www.devze.com 2023-01-01 06:23 出处:网络
This is my jquery code jQuery(document).ready (function() { // post $(\'.post\').bind(\'mouseenter mouseleave\', function() {

This is my jquery code

jQuery(document).ready (function() {

   // post
    $('.post').bind('mouseenter mouseleave', function() {
        $(this).filter('.btn').toggleClass('hidden');
    });


});

It works great on a norm开发者_JS百科al document. but When I load some HTM: (i.e some divs with .post attributes) using ajax and embed it into my DOM.

The above code doesnt work with those divs.


Try using live:

jQuery(document).ready (function() {
    $('.post').live('mouseenter mouseleave', function() {
        $(this).filter('.btn').toggleClass('hidden');
    });
});

Or better yet delegate

jQuery(document).ready (function() {
    $('#posts').delegate('.post','mouseenter mouseleave', function() {
        $(this).filter('.btn').toggleClass('hidden');
    });
});


Your timing is probably off as the div with .post attributes must actually exist in the dom before you can bind anything to it.

0

精彩评论

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