Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取具有特定ID的每个元素(jQuery)_Javascript_Jquery_Html - Fatal编程技术网

Javascript 获取具有特定ID的每个元素(jQuery)

Javascript 获取具有特定ID的每个元素(jQuery),javascript,jquery,html,Javascript,Jquery,Html,我需要获取具有特定id的每个元素,获取对象的父对象,并设置其id 我该怎么做 我有以下代码: <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_selecte

我需要获取具有特定id的每个元素,获取对象的父对象,并设置其id

我该怎么做

我有以下代码:

<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_链接找到所有锚元素,获取列表项元素[li]的父元素,并将其id设置为selected。我将如何使用jQuery实现这一点?我将使用条件来确定是否允许li元素实际获取新ID。如果URL与锚元素的href属性匹配。

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>

您需要为此使用类。在HTML中,不允许多次使用ID。

ID属性在整个XHTML文档中应该是唯一的,因此这个问题实际上是无效的

尽管如果你真的坚持,这可能会奏效:

$("[id=xx]")

虽然我真的很感谢你的评论,但是你没有为我提供像Teneff这样的所有东西的代码。谢谢你!有一些观点,我现在就去修改代码;
$('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');

    }

});