2010-09-11 67 views
0

我有一個div內的錨鏈接。我希望錨鏈接和div分別處理onclick事件,但現在單擊錨鏈接也會觸發div的onclick事件。我如何防止這種情況?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

輝煌。謝謝,羅伯特 – 2010-09-11 17:28:01

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/

0

它可能是由於你的錨沒有正確關閉。或者,它肯定不會幫助