0

我在 div 中有一个锚链接。我希望锚链接和 div 分别处理 onclick 事件,但是现在单击锚链接也会触发 div 的 onclick 事件。我该如何防止这种情况?

这是代码:

<html>
     <头部>
     <风格>
     #盒子 {
          背景颜色:#ccffcc;
          宽度:400px;
          高度:200px;
     }
     </style>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
     </脚本>
     <script type="text/javascript">
          $(文档).ready(函数() {
               $("#mailto").click(函数(事件){
                    // 如果单击,则正确打开电子邮件客户端
                    $("a[@href^='http']").attr('target','_blank');
                    返回(假);
               });

               $("#box").click(function() {
                    // 总是转到主页,即使点击了#mailto id
                    window.location = '/index.php';
               });
          });
     </脚本>
     </head>
     <正文>
     <div id="盒子">
          <a href="mailto:someone@psomewhere.com" id="mailto">someone@psomewhere.com
    </div>
     </正文>
</html>

有没有办法让我在加载 mailto 后停止执行代码?

谢谢!

约翰

4

3 回答 3

0

该事件正在冒泡 DOM 树,e.stopPropagation();将停止它。

$("#mailto").click(function(event) {
    event.stopPropagation();
    // 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';
});​

小提琴 http://jsfiddle.net/uwJXK/
关于 stopPropagation() http://api.jquery.com/event.stopPropagation/

于 2010-09-11T16:18:05.187 回答
0

这可能是由于您的锚没有正确关闭。或者它肯定不会有帮助

于 2010-09-11T16:18:12.073 回答
0

你需要确保你的 html 是有效的,所以完成 a 标签:

<a href="mailto:someone@psomewhere.com" id="mailto">someone@psomewhere.com<a/>

如果这仍然导致问题,试试这个。

$("#mailto").click(function(event)
{
    event.stopPropagation();
    if(event.srcElement == 'HTMLAnchorElement')
    { 
        //Process
    }
});
于 2010-09-11T16:19:54.510 回答