2011-06-15 62 views
4

我正在循環顯示一個表單並顯示與我選擇的ID匹配的內容。問題是一些div包含多個id,在這種情況下它停止工作。有任何想法嗎?謝謝。當元素有多個ID時匹配

jQuery代碼:

$('#myForm').find('div').each(function() { 
     var myId = $(this).attr('id'); 

     /* This will work */ 
     if (myId == "Select1"){ 
       $(this).removeClass("hideMe"); 
       $(this).addClass("showMe"); 
       } 
     /* This does not work */ 
     else if (myId == "Select4"){ 
       $(this).removeClass("hideMe"); 
       $(this).addClass("showMe"); 
       } 
     else{} 

     }); 

HTML代碼:

<div class="hideMe" id="Select1"> 
<p>Some Content</p> 
</div> 

<div class="hideMe" id="Select2 Select3 Select4 Select5"> 
<p>Some Content</p> 
</div> 
+4

我會第一個說,WTF – Jason 2011-06-15 21:19:20

+0

問題是divs不能有多個ID。看到這個問題:http://stackoverflow.com/q/192048/206403 – 2011-06-15 21:19:29

+0

根據規範,一個'id'不能包含空格。所以你的HTML無效。如果你做了無效的HTML,這意味着從現在起發生的所有事情都是未定義的行爲。而且,嘿,這種行爲在瀏覽器中可能會有所不同。所以首先修復你的HTML。 – 2011-06-15 21:19:39

回答

10

有 「多IDS」 沒有這樣的事。

https://developer.mozilla.org/en/XUL/Attribute/id

根據標準,該id屬性內的任何字符串數據被視爲值的一部分。

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".")

參考:http://www.w3.org/TR/REC-html40/types.html#type-name

還有另外一種方式,但!你可以有各種各樣的類名,你可以使用jQuery通過類名來獲取元素。

HTML

<div class="hideMe Select1"> 
<p>Some Content</p> 
</div> 

<div class="hideMe Select2 Select3 Select4 Select5"> 
<p>Some Content</p> 
</div> 

的Javascript

$('.Select2')[0] 

的是,[0]部分是因爲當你通過類名的元素,有可以是幾個。 jQuery選擇器返回一個數組,所以你只是抓住第一個。

+1

對於它的價值 - 不要使用冒號或圓點,因爲它不可能爲元素編寫普通的選擇器。 #id.something將'something'視爲一個類,#id:將某物視爲僞選擇器。 – Beejamin 2011-06-15 21:22:37

1

您不能有多個ID。但是,如果您願意,您可以擁有多個課程。

0

ID是獨特和元素只能有1 ID

改爲使用多個類。

0

一個元素不應該有多個唯一的標識符,這就是爲什麼它實際上被稱爲一個ID:要辨別所有其他元素。無論如何,您必須測試myId是否包含Select4,而不是測試相等性。

相關問題