2010-09-11 3 views
0

У меня есть привязная ссылка внутри div. Я хотел бы, чтобы и привязка, и div обрабатывали события onclick отдельно, но прямо сейчас нажатие на ссылку привязки также вызывает событие onclick для div. Как я могу это предотвратить?jquery разделить события 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 загружается?

Спасибо!

Джон

ответ

0

вы должны убедиться, что ваш HTML является действительным, так закончить тег от:

<a href="mailto:[email protected]" id="mailto">[email protected]<a/> 

, и если это все еще вызывает проблемы, попробуйте это.

$("#mailto").click(function(event) 
{ 
    event.stopPropagation(); 
    if(event.srcElement == 'HTMLAnchorElement') 
    { 
     //Process 
    } 
}); 
+0

Блестящий. Спасибо, Роберт –

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'; 
});​ 

Fiddlehttp://jsfiddle.net/uwJXK/
О stopPropagation()http://api.jquery.com/event.stopPropagation/

0

Это может быть из-за вашего якоря не закрыта должным образом. Или это, конечно, не будет помогать