2011-05-25 78 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]")