JS mouseenter触发两次 [英] JS mouseenter triggered twice
问题描述
问题是关于事件mouseenter被触发两次。
代码在这里: http://jsfiddle.net/xyrhacom/
The problem is about event mouseenter which is triggered twice. The code is here : http://jsfiddle.net/xyrhacom/
HTML:
<div id="elt1" class="elt" val="text1">
text1
<div id="elt2" class="elt" val="text2">
text2
<div>
</div>
JS:
$(document).ready(function() {
$(".elt").mouseenter(function() {
console.log($(this).attr('val'));
});
})
问题是事件链接到类属性,所以它被触发为每个类,但我需要找到一种方式来考虑只是为孩子触发的事件。
I understand the problem is the event is linked to the class attribute so it is triggered for each class, but I need to find a way to consider just the event triggered for the child.
在示例中,当鼠标悬停text2时,它显示在控制台text2 text1中,但是我想要找到一种只显示text2(保持相同的HTML代码)的方式
In the example, when mouseover text2, it displays in the console 'text2 text1' but I want to find a way to only display 'text2' (keeping the same HTML code)
推荐答案
使用 stopPropagation() < /强>;防止事件冒泡DOM树,
use stopPropagation(); Prevents the event from bubbling up the DOM tree,
$(document).ready(function() {
$(".elt").mouseenter(function(e) {
e.stopPropagation();
console.log($(this).attr('val'));
});
})
这篇关于JS mouseenter触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!