2011-07-22 28 views
5

的Html如何將onclick回調附加到div而不是div內的鏈接上?

<div class='item_container'> 

[...bunch of links and pictures...] 
<a class='item_owner'>John Doe</a> 

</div> 

的Javascript

/** 
    Bind the onclick only if you hover on the item since we got a lot 
    of items and several events and plugins to setup on them. 
*/ 
$('.item_container').live('mouseenter', function(e){ 
    $this = $(this); 
    if (!$this.data('isSetup')) { 
    $this.click(function(e){ 
     // do magic 
     return false; 
    }); 
    [... a lot of other stuff] 
    $this.data({'isSetup': true}); 
    } 
}); 

當然,當我點擊在div任何地方,它會執行 '變魔術'。感謝return false,如果我點擊div中的任何鏈接,它仍然執行'do magic'並且不會更改頁面,這是預期的行爲。

但是有一個鏈接是假設實際更改頁面的所有者鏈接。麻煩的是,在我目前的設置下,我阻止了它的工作。

+0

不,如果你使用'e.preventDefault()'它做? – ianbarker

+0

檢查單擊元素的類型... this.tagName。如果是鏈接不返回false ... – 2GDev

+0

@ 2GDev:做出答案。如果它的工作,你會得到代表 –

回答

4

您需要停止從鏈接到父節點.item_container的事件傳播。

此塊添加到代碼:

$('.item_container a.item_owner').live('click', function(e){ 
e.stopPropagation(); 
}); 
+0

性能明智$('div.item_container a.item_owner')將是更好的選擇 – MaMa

+0

這將工作很好,如果我沒有其他鏈接在div不應該停止傳播。只有所有者鏈接必須觸發頁面更改。其他人不應該和點擊他們應該執行「做魔術」,就像該地區的其他地方一樣。 –

+0

@ e-satis:檢查更新的答案。 – Chandu