简体   繁体   English

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

[英]Click event on the span appended during the mouseover is not firing

I append a span to a div on mouseover , and I simply want to trigger a click on the nested span. 我在mouseover将一个span附加到div ,我只想触发嵌套跨度上的单击。 It feels like I've tried everything out of luck. 感觉就像我已经尝试了一切运气。

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

I've found a couple of similar but they unfortunately didn't work out either. 我发现了几个类似但不幸的是他们也没有成功。

Change your mouseover to mouseenter and use event delegation mouseover更改为mouseenter并使用事件委派

$('.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 演示

Using mouseover, it gets triggered even when you hover over the child span and it keeps on removing and appending the span. 使用鼠标悬停,即使您将鼠标悬停在子跨距上并且它继续移除并附加跨度,它也会被触发。

from doc 来自doc

The mouseenter event differs from mouseover in the way it handles event bubbling. mouseenter事件与处理事件冒泡的方式不同于mouseover。 If mouseover were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered. 如果在此示例中使用鼠标悬停,则当鼠标指针移过Inner元素时,将触发处理程序。 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. 另一方面,mouseenter事件仅在鼠标进入绑定的元素而不是后代时触发其处理程序。 So in this example, the handler is triggered when the mouse enters the Outer element, but not the Inner element. 因此,在此示例中,当鼠标进入外部元素而不是内部元素时,将触发处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM