2017-06-05 158 views
0

下面是一個HTML結構我不能改變:jQuery選擇了李其第一個孩子是一個跨度

enter image description here

我成功地連接一個click事件處理那些li的,就像這樣:

$(document).on("click", "#menu li.top-level", function (e) { 

    // whatever code 

}); 

不過,我不希望對有z-index: auto由處理程序捕獲li的點擊次數。我嘗試這樣做:

$(document).on("click", "#menu li.top-level[style='z-index: auto;']", function (e) { 

$(document).on("click", "#menu li[style='z-index: auto;'].top-level", function (e) { 

,但沒有運氣。

此外,li的我想抓在處理程序有一個<a>作爲第一個孩子,而其他人有一個<span>。也許這可以用來幫助?

編輯

下面是HTML結構:我想趕上上li,而不是其他一個

enter image description here

+0

我認爲你需要':not()'ie'「#menu li.top-level:not([style ='z-index:auto;'])」' – Satpal

+0

Wha t @Satpal說 - 看起來你有你的標準倒退。 – BoltClock

回答

1

如果你想li元素的第一個孩子是有保證成爲a,而那些你不會的總是span,你最好基於該條件進行選擇,因爲他們的樣式中的匹配元素通常是脆弱:

$(document).on("click", "#menu li.top-level:has(> a:first-child)", function (e) { 
+0

它仍然捕獲在兩個點擊:檢查我的編輯 – chiapa

+0

@chiapa:如果任何你的編輯表明,這不應該發生,我的答案應該工作。 – BoltClock

+0

你是對的,我忘記了最後一個括號。謝謝 – chiapa

2

當你不想選擇具有style='z-index: auto;'元素,然後使用:not()選擇和:has()具有元素錨點目標的第一個孩子

$(document).on("click", "#menu li.top-level:not([style='z-index: auto;']):has(> a:first-child)", handler); 

$(document).on("click", "#menu li.top-level:not([style='z-index: auto;']):has(> a:first-child)", function() { 
 
    console.log($(this).text()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul id="menu"> 
 
    <li class="top-level"><a href="#">1</a></li> 
 
    <li class="top-level"><span>2</span></li> 
 
    <li class="top-level" style='z-index: auto;'><a href="#">3</a></li> 
 
</ul>

+0

它仍然捕獲點擊兩個:檢查我的編輯 – chiapa

相關問題