3

.thumb当单击.button

这是jquery函数:

$('.thumb').hover(function() {
    $(this).find('.close').fadeIn();
}, function() {
    $(this).find('.close').fadeOut();
});
$('.close').click(function() {
    $(this).parent().fadeOut('slow');
});
$('.button').click(function() {
    $html = '<div class="thumb">';
    $html += '<img src="http://findicons.com/files/icons/1979/social/50/wordpress.png" />';
    $html += '<div class="close">X</div>';
    $html += '</div>';
    $('.box').append($html);
});

http://jsfiddle.net/UfyQq/

我遇到此代码的障碍是附加的 div 不服从悬停事件或在.close

我真的很感谢这里的一些帮助,谢谢!

4

3 回答 3

4

问题是附加事件侦听器时附加的内容不存在。在父元素上使用jQuery.on()来解决这个问题。

检查这个工作的jsFiddle

$('.box').on('mouseenter','.thumb',function() {
    $(this).find('.close').fadeIn();
});

$('.box').on('mouseleave','.thumb',function() {
    $(this).find('.close').fadeOut();
});
于 2013-07-07T16:09:45.580 回答
2

您必须使用委托:

演示

$('.box').on({
    mouseenter: function () {
        $(this).find('.close').fadeIn();
    },
    mouseleave: function () {
        $(this).find('.close').fadeOut();
    }
}, '.thumb');

$('.box').on('click','.close',function () {
    $(this).parent().fadeOut('slow');
});
于 2013-07-07T16:11:03.003 回答
0

改变:

$('.thumb').hover(function() {
    $(this).find('.close').fadeIn();
}, function() {
    $(this).find('.close').fadeOut();
});
$('.close').click(function() {
    $(this).parent().fadeOut('slow');
});
$('.button').click(function() {
    $html = '<div class="thumb">';
    $html += '<img src="http://findicons.com/files/icons/1979/social/50/wordpress.png" />';
    $html += '<div class="close">X</div>';
    $html += '</div>';
    $('.box').append($html);
});

至:

$('.thumb').hover(function() {
    $(this).find('.close').fadeIn();
}, function() {
    $(this).find('.close').fadeOut();
});
$('.close').click(function() {
    $(this).parent().fadeOut('slow');
});
$('.button').click(function() {
    $html = '<div class="thumb">';
    $html += '<img src="http://findicons.com/files/icons/1979/social/50/wordpress.png" />';
    $html += '<div class="close">X</div>';
    $html += '</div>';
    $('.box').append($html);
    $('.thumb').hover(function() {
    $(this).find('.close').fadeIn();
}, function() {
    $(this).find('.close').fadeOut();
});
$('.close').click(function() {
    $(this).parent().fadeOut('slow');
});
});

这将再次附加事件。

于 2013-07-07T16:13:37.197 回答