当单击.button
时,我正试图使用jquery将.thumb
附加到另一个最后的div中
这是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
上使用点击功能
我真的很感激这里的帮助,谢谢!
问题是在附加事件侦听器时附加的内容不存在。在父元素上使用jQuery的.on()
来修复此问题。
检查这个工作jsFiddle
$('.box').on('mouseenter','.thumb',function() {
$(this).find('.close').fadeIn();
});
$('.box').on('mouseleave','.thumb',function() {
$(this).find('.close').fadeOut();
});
您必须使用委派:
演示
$('.box').on({
mouseenter: function () {
$(this).find('.close').fadeIn();
},
mouseleave: function () {
$(this).find('.close').fadeOut();
}
}, '.thumb');
$('.box').on('click','.close',function () {
$(this).parent().fadeOut('slow');
});
更改:
$('.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');
});
});
这将再次附加事件。