jQuery基于li类更改Href

时间:2015-01-30 09:28:27

标签: jquery html css

HTML结构:

<li class="page_item page-item-7 page_item_has_children">
<a href="http://localhost/myproject/parent/">Parent</a>
<i class="fa fa-caret-right"></i>
<ul class="children">
<li class="page_item page-item-9">
<a href="http://localhost/myproject/parent/Child One/">Child One</a>
</li>
<li class="page_item page-item-10">
<a href="http://localhost/myproject/parent/Child Two/">Child Two</a>
</li>
</ul>
</li>

jQuery的:

jQuery(document).ready(function() {
            jQuery('li.page_item_has_children a[href*="/parent/"]').attr("href", "#");
});

以上代码可以使用并更改Parent的网址,但同时也会更改其Children的网址。所以生成的html是

输出:

<li class="page_item page-item-7 page_item_has_children">
<a href="#">Parent</a>
<i class="fa fa-caret-right"></i>
<ul class="children">
<li class="page_item page-item-9">
<a href="#">Child One</a>
</li>
<li class="page_item page-item-10">
<a href="#">Child One</a>
</li>
</ul>
</li>

如何只更改Parent href而不更改其相关子元素?

2 个答案:

答案 0 :(得分:2)

试试这个:您需要使用>来寻找直接孩子

jQuery(document).ready(function() {
   jQuery('li.page_item_has_children > a[href*="/parent/"]').attr("href", "#");
});

答案 1 :(得分:1)

立即使用 child selector >

  

选择由“parent”指定的元素“child”指定的所有直接子元素。

jQuery(document).ready(function() {
        jQuery('li.page_item_has_children > a').attr("href", "#");
});
相关问题