2013-05-18 54 views
0

我有以下設置jQuery的,如果李被點擊並不僅火的標籤

<ul> 
    <li><a href="http://www.example.com">Example</a></li> 
    <li><a href="http://www.example2.com">Example2</a></li> 
</ul> 

李的的寬度由CSS設置爲400像素;

我試圖寫一些jquery,只有li被點擊纔會觸發,但不是a標籤。

對此提出建議?

回答

1

當你在單擊處理事件,看看event.target/event.originalTarget

這應該給你一個指示哪個元素導致事件的信息,你可以處理它或忽略它。

function clickHanlder (e) 
{ 
    if (e.target.tagName != "A") { return; } 
} 
1

子元素上使用e.stopPropagation();

$('li').click(function(){ 
    alert('This will be alerted on the li, not the anchor inside'); 
}); 

$('li a').click(function(event){ 
    event.stopPropagation(); 
}); 

jsFiddle here.

+0

或'e.preventDefault();' – Dom

+0

@Dom可以做,我覺得stopPropagation()工作得很好,在這種使用情況下,雖然 – lifetimes

+0

兩者都是有效:--D – Dom

0

您也可以在函數中傳遞「e」,然後檢查目標。剛剛閱讀Dory的評論,我同意。在我看來,這是最好的路線,並始終有效。

$('element').on('click', function (e) { 
    if(e.target == 'check the tag here'){ 
     // do something. 
    } 
}); 
0
$('li').click(function(){ 
alert('li here'); 
}); 
$('ul li a').click(function(){ 
return false; 
}); 
相關問題