2012-08-12 59 views
11

我想要做的是選擇文檔上的所有輸入按鈕,除了那些位於特定ID下的按鈕。如何選擇除特定ID以外的所有輸入?

實施例:

<body> 
<input type="button"> 

<div id="something"> 
    <input type="button"> 
</div> 
<div id="something2"> 
    <input type="button"> 
</div> 


<input type="button"> 
<input type="button"> 
<input type="button"> 
</body> 

例如,我想選擇所有的輸入,除了那些位於下<div>id是「東西」。

我已經試過:

1) $('input[type="button"]:not(:parent(#something))').addCSS(); 

2) $('input[type="button"] :not(#something input[type="button"])') 

與其他類似的方法

+0

[JQuery Selector for not「wrapped」elements]的可能的重複(http://stackoverflow.com/questions/11924672/jquery-selector-for-not-wrapped-elements) – Blazemonger 2013-02-27 21:12:36

回答

18

你可以做這樣的(相對有效)。

$("input[type=button]").filter(function() { 
    return $(this).closest("#something").length == 0; 
}); 

首先,你的所有input[type=button]元素,然後刪除那些#something作爲父母。

另一種可能性是:

$("input[type=button]").not("#something input[type=button]") 

你不得不來測試,看看哪個更有效,但無論是將工作。

工作兩者的演示:http://jsfiddle.net/jfriend00/fjxDb/

1

也許這個作品:$(":not(#something) input[type=button]")

+1

我想知道效率這是因爲文檔中的幾乎每個對象(除了一個)都會匹配':not(#something)'。 – jfriend00 2012-08-12 23:39:45

+1

@ jfriend00而且它也行不通http://jsfiddle.net/Zt4Qd/ – undefined 2012-08-12 23:44:29

+0

只要給它一個隨機鏡頭......也許你會有一些運氣。下次,如果它已經很容易重建,我建議你自己嘗試一下。 – Kiruse 2012-08-12 23:46:17

6

你幾乎那裏,你需要做的一切是你之前刪除的空間:沒有。

$('input[type="button"]:not(#something input[type="button"])') 

我知道這是一個老問題,但它首先在谷歌顯示出來,並使用jQuery的。不()作爲公認的答案表示並不總是一個選項。

+0

總是歡迎改進! :D – 2016-04-28 11:41:13

+0

爲什麼jQuery的'.not()'有時不是一個選項?這是一個jQuery問題,所以你總是可以在'jQuery中使用'.not()',對吧? – jfriend00 2016-09-02 05:27:17

+0

當你想動態地處理事件時,也可以在**應用它之後添加**的元素,通常使用$(document).on('theEvent','theSelector')。在那裏,不可能將選擇器與.not()結合使用,而可以使用:不在選擇器中。 – 2016-09-03 06:07:41

相關問題