【问题标题】:Hover event not working after append() div contentappend() div 内容后悬停事件不起作用
【发布时间】:2013-07-05 00:38:57
【问题描述】:

单击.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 上使用点击功能

非常感谢您的帮助,谢谢!

【问题讨论】:

  • 我认为浏览器在开始时为每个元素设置了事件,如果您在加载页面后附加元素,它将无法正常工作。最好在创建新元素后设置悬停事件或为创建元素的上一级设置悬停
  • 我使用了单独的组件,包含悬停事件,点击功能和$.ajax,感谢回复!

标签: jquery jquery-hover


【解决方案1】:

你必须使用委托:

DEMO

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

$('.box').on('click','.close',function () {
    $(this).parent().fadeOut('slow');
});

【讨论】:

  • 如何在.close上使用点击功能
【解决方案2】:

改变:

$('.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');
});
});

这将再次附加事件。

【讨论】:

  • 这会将.close点击事件多次附加到现有按钮。
  • 我知道,但是没有内存交换因为它会覆盖以前的事件侦听器。 -当然有很多漂亮的解决方案。
  • 是的,但我附上$.ajax 不应用作解决我的问题的方法。谢谢!
【解决方案3】:

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

check this working jsFiddle

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

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

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 2016-06-04
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 2016-08-31
    相关资源
    最近更新 更多