停止Javascript中的事件冒泡 [英] Stop event bubbling in Javascript
问题描述
我有一个类似html的结构:
I have a html structure like :
<div onmouseover="enable_dropdown(1);" onmouseout="disable_dropdown(1);">
My Groups <a href="#">(view all)</a>
<ul>
<li><strong>Group Name 1</strong></li>
<li><strong>Longer Group Name 2</strong></li>
<li><strong>Longer Group Name 3</strong></li>
</ul>
<hr />
Featured Groups <a href="#">(view all)</a>
<ul>
<li><strong>Group Name 1</strong></li>
<li><strong>Longer Group Name 2</strong></li>
<li><strong>Longer Group Name 3</strong></li>
</ul>
</div>
我希望仅从主div触发onmouseout
事件,而不是从div中的'a'或'ul'或'li'标记触发!
I want the onmouseout
event to be triggered only from the main div, not the 'a' or 'ul' or 'li' tags within the div!
我的onmouseout
函数如下:
function disable_dropdown(d)
{
document.getElementById(d).style.visibility = "hidden";
}
有人可以告诉我如何阻止事件冒泡吗?我尝试了其他站点上提供的解决方案(stopPropogatio
等),但是我不确定如何在这种情况下实现它们.
Can someone please tell me how I can stop the event from bubbling up? I tried the solutions (stopPropogatio
etc) provided on other sites, but I'm not sure how to implement them in this context.
任何帮助将不胜感激.
推荐答案
The events that you really want to use are onmouseenter and onmouseleave, however they are not implemented in all browsers. You could look to implement them yourself, however you would in this case be better off using a library that has already solved the problem cross browser for you. So, in jQuery
<div id="main">
My Groups <a href="#">(view all)</a>
<ul>
<li><strong>Group Name 1</strong></li>
<li><strong>Longer Group Name 2</strong></li>
<li><strong>Longer Group Name 3</strong></li>
</ul>
<hr />
Featured Groups <a href="#">(view all)</a>
<ul>
<li><strong>Group Name 1</strong></li>
<li><strong>Longer Group Name 2</strong></li>
<li><strong>Longer Group Name 3</strong></li>
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$('#main').hover(function() { enable_dropdown(1); }, // mouseenter
function() { disable_dropdown(1); }); // mouseleave
</script>
这篇关于停止Javascript中的事件冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!