的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'並且不會更改頁面,這是預期的行爲。
但是有一個鏈接是假設實際更改頁面的所有者鏈接。麻煩的是,在我目前的設置下,我阻止了它的工作。
不,如果你使用'e.preventDefault()'它做? – ianbarker
檢查單擊元素的類型... this.tagName。如果是鏈接不返回false ... – 2GDev
@ 2GDev:做出答案。如果它的工作,你會得到代表 –