初始状态是我有一个id数组[45、3、678]和一个div标记,里面有很多元素,它们是嵌套的,并且每个都有唯一的id。我只需要为那些其ID在ID数组中的元素添加“选定”类。我怎样才能做到这一点?
<div id="parent-class">
<details id=1>
<ul id=2>
<details id=3></details>
<details id=4></details>
<details id=5></details>
...
</ul>
</details>
<details id=56>
<ul id=57>
<details id=58></details>
<details id=59></details>
<details id=60></details>
...
</ul>
</details>
</div>
$('div#parent-class').ready(function () {
var options = [45, 3, 678];
/* Here I need to loop through all children and assign class for those elements whose id is in array options*/
$('div#parent-class').children().each(function(){
var id = $(this).attr('id');
if ($.inArray(id, options)) $(this).addClass('selected');
});
});
非常感谢您的帮助
答案 0 :(得分:0)
@freedomn-m评论说,您需要您的ID至少包含一个alpha角色,因此我建议您更改ID,对于循环,您只需使用属性选择器选择数组中的元素
$('div#parent-class').ready(function () {
var options = [56, 3, 60];
options.forEach(function(v,i) {
$('[id="item_'+v+'"]').addClass('selected');
//or $("#item_" + v).addClass('selected');
})
});
.selected{border:1px solid red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent-class">
<details id="item_1">
<ul id="item_2">
<details id="item_3"></details>
<details id="item_4"></details>
<details id="item_5"></details>
...
</ul>
</details>
<details id="item_56">
<ul id="item_57">
<details id="item_58"></details>
<details id="item_59"></details>
<details id="item_60"></details>
...
</ul>
</details>
</div>