2011-05-25 52 views
0

我需要獲取具有特定ID的每個元素,獲取該對象的父級並設置其ID。獲取具有特定ID的每個元素(jQuery)

我該怎麼做?

我有這樣的代碼:

<li id="edge_top">&nbsp;</li> 
<!-- Menu Items Here  --> 
<li id="not_selected"><a id="selection_link" href="index.htm">Home</a></li> 
<li id="not_selected"><a id="selection_link" href="page1.htm">Subitem 1</a></li> 
<li id="not_selected"><a id="selection_link" href="page2.htm">Subitem 2</a></li> 
<!-- Menu Items End Here --> 
<li id="edge_bottom">&nbsp;</li> 

我需要找到所有id爲「selection_link」錨定體,獲取父(以下簡稱「列表項」元素[李]),並設置其ID來「選擇」。我將如何與jQuery做到這一點?我將使用條件來確定li元素是否實際上被允許獲得新的ID。 (如果URL匹配錨元素的href屬性)。

回答

1
$('li a').each(function(){ 

    if ($(window).attr('location').href.match($(this).attr('href'))) { 
     //example with class 
     $(this).parent().addClass('selected'); 
     // example with id 
     $(this).parent().attr('id', 'selected'); 

    } 

}); 
11

HTML規範指定一個ID只能應用於1個元素。你不能有多個具有相同ID的元素。

在這種情況下,最好使用類。根據你的代碼一個例子:

由類選擇:

$(".classname")... 

編輯

<li class="edge_top">&nbsp;</li> 
<!-- Menu Items Here  --> 
<li class="not_selected"><a class="selection_link" href="index.htm">Home</a></li> 
<li class="not_selected"><a class="selection_link" href="page1.htm">Subitem 1</a></li> 
<li class="not_selected"><a class="selection_link" href="page2.htm">Subitem 2</a></li> 
<!-- Menu Items End Here --> 
<li class="edge_bottom">&nbsp;</li> 

<script type="text/javascript"> 
$(document).ready(function(){ 
    $(".selection_link").parent().removeClass("not_selected").addClass("selected") 
}); 
</script> 
+0

雖然我很欣賞你的意見,但你沒有爲我提供一切都像Teneff的代碼。雖然謝謝!有一些觀點,我現在就去改變我的代碼;) – FreeSnow 2011-05-25 13:38:04

2

您需要使用類這一點。在HTML中,您不允許多次使用ID。

2

id屬性在您的XHTML文檔中應該是唯一的,所以這個問題並不真正有效。

雖然這工作,如果你真的堅持:

$("[id=xx]") 
相關問題