javascript - 鼠标悬停期间附加的跨度上的单击事件未触发

标签 javascript jquery

我将 span 附加到 mouseover 上的 div,我只想触发对嵌套 span 的点击。 感觉我已经尝试了所有的运气。

http://jsfiddle.net/NHHSX/1/

我找到了几个类似的,但不幸的是它们也没有成功。

最佳答案

mouseover 更改为 mouseenter 并使用事件委托(delegate)

$('.container').on('mouseenter', function (e) {
    $(this).append('<span class="span1">I want this to be clickable..</span>');
}).on('mouseleave', function (e) {
    $(this).find('.span1').remove();
});

$('.container').on('click', '.span1', function () {
    alert("click");
});

Demo

使用鼠标悬停,即使您将鼠标悬停在子跨度上,它也会被触发,并且它会继续删除和附加跨度。

来自 doc

The mouseenter event differs from mouseover in the way it handles event bubbling. If mouseover were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseenter event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the Outer element, but not the Inner element.

关于javascript - 鼠标悬停期间附加的跨度上的单击事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026539/

相关文章:

javascript - 使用javascript变量设置元素高度

javascript - 倒计时 JavaScript

jQuery:更改特定文本颜色

json - Jquery $.Ajax 卡住浏览器

javascript - 为什么这个函数没有被调用?

javascript - 如果在jquery中不起作用

javascript - 为什么这条 Canvas 线在 Chrome 中有颜色,但在 Firefox 中没有?

javascript - jQuery:无法选择附加的选择选项

javascript - 无需刷新即可运行 PHP 脚本的最简单方法

javascript - 使用 jQuery 提取 HTML 标签外的文本