jquery分离包装元素的onclick事件
我在 div 中有一个锚链接。我希望锚链接和 div 分别处理 onclick 事件,但现在单击锚链接也会触发 div 的 onclick 事件。我该如何防止这种情况?
这是代码:
<html> <head> <style> #box { background-color: #ccffcc; width: 400px; height: 200px; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { $("#mailto").click(function(event) { // correctly opens an email client if clicked $("a[@href^='http']").attr('target','_blank'); return( false ); }); $("#box").click(function() { // always goes to the home page, even if the #mailto id is clicked window.location = '/index.php'; }); }); </script> </head> <body> <div id="box"> <a href="mailto:[email protected]" id="mailto">[email protected] </div> </body> </html>
有没有办法让我在加载 mailto 后停止执行代码?
谢谢!
约翰
I have an anchor link inside a div. I would like both the anchor link and div to process onclick events separately, but right now clicking on the anchor link also triggers the onclick event for the div. How do I prevent this?
Here's the code:
<html> <head> <style> #box { background-color: #ccffcc; width: 400px; height: 200px; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { $("#mailto").click(function(event) { // correctly opens an email client if clicked $("a[@href^='http']").attr('target','_blank'); return( false ); }); $("#box").click(function() { // always goes to the home page, even if the #mailto id is clicked window.location = '/index.php'; }); }); </script> </head> <body> <div id="box"> <a href="mailto:[email protected]" id="mailto">[email protected] </div> </body> </html>
Is there a way for me to stop execution of the code after the mailto is loaded?
Thanks!
John
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能是由于您的锚没有正确关闭。或者它肯定不会有帮助
It might be due to your anchor not being closed properly. Or it certainly won't be helping
该事件正在 DOM 树中冒泡,
e.stopPropagation();
将停止该事件。小提琴 http://jsfiddle.net/uwJXK/
关于 stopPropagation() http://api.jquery.com/event。停止传播/
The event is bubbling up the DOM tree,
e.stopPropagation();
will stop that.Fiddle http://jsfiddle.net/uwJXK/
About stopPropagation() http://api.jquery.com/event.stopPropagation/
您需要确保您的 html 有效,因此请完成 a 标记:
如果仍然导致问题,请尝试此操作。
you need to make sure your html is valid, so finish the a tag off:
and if that still causes problems try this.