我将 span
附加到 mouseover
上的 div
,我只想触发对嵌套 span 的点击。
感觉我已经尝试了所有的运气。
我找到了几个类似的,但不幸的是它们也没有成功。
最佳答案
将 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/