JS mouseenter触发两次

编程入门 行业动态 更新时间:2024-10-24 10:20:11
本文介绍了JS mouseenter触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

问题是关于事件mouseenter被触发两次。 代码在这里: jsfiddle/xyrhacom/

The problem is about event mouseenter which is triggered twice. The code is here : jsfiddle/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触发两次

本文发布于:2023-11-27 13:02:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638189.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   JS   mouseenter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!