2011-07-31 22 views
1

我有以下的HTML。是這是適用於jQuery的HTML

div#main-content div#right-col div#post-show div#post-img div#post-img-large{ 

} 
div#main-content div#right-col div#post-show div#post-img div#post-img-large 
    img#post-img-large{ 
} 

正如你所看到的,我使用相同的ID爲div和img。

這是允許的嗎?我知道它可以正常工作,但如果我引用id post-img-large,jQuery會感到困惑嗎?

回答

3

ID應該不會超過一個元素上的任何給定的頁面上使用。它們被用來唯一標識元素。如果你使用jQuery,總是有方法通過使用更多信息(div#ID,img#ID)來限定你的選擇器來選擇你想要的元素 - jQuery不會被混淆,但你應該堅持標準,不要重複使用ID。

來自W3C: http://www.w3.org/TR/html4/struct/global.html(HTML4,但它仍然適用)

7.5.2 Element identifiers: the id and class attributes 

Attribute definitions 

id = name [CS] 
This attribute assigns a name to an element. This name must be unique in a document. 
class = cdata-list [CS] 
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters. 
3

從以往的經驗:

對於ID選擇,jQuery使用JavaScript函數 的document.getElementById(),這是非常有效的。當另一個 選擇器連接到id選擇器(例如h2#pageTitle)時,jQuery 會在將該元素標識爲 匹配之前執行附加檢查。

每個id值只能在文檔中使用一次。如果多於 一個元素被分配了相同的ID,那麼使用該ID 的查詢將僅選擇DOM中的第一個匹配元素。但是,不應該依賴此行爲 ;具有多個使用相同ID的 元素的文檔無效。

來源:http://api.jquery.com/id-selector/

0

這不是一個有效的HTML,id s必須是唯一的。

是的,有可能是因爲重複的ID,jquery無法按預期工作。事實上,就在幾天前,我在這裏看到了一個功能破壞的問題。