使用jQuery在嵌套列表中选择所有未链接的项目 [英] Select all unlinked items in a nested list with jquery
问题描述
我有以下HTML
<ul>
<li><a ...>item 1</a></li>
<li>item 2
<ul>
<li><a ...>item 2-a</a></li>
<li><a ...>item 2-b</a></li>
</ul>
</li>
<li><a ...>item 3</a></li>
<li>item 4
<ul>
<li><a ...>item 4-a</a></li>
<li><a ...>item 4-b</a></li>
</ul>
</li>
<li><a ...>item 5</a></li>
<li><a ...>item 6</a></li>
</ul>
我想使用.has
用jquery向'item 2'和'item 4'添加一个类,但是找不到方法.
I want to add a class to 'item 2' and 'item 4' with jquery using .has
but can't find a way.
我想澄清一下我的问题: 我有一个嵌套列表,其中有一些项目未链接,但项目数量未知.我想为所有不同的项目添加一个类.
I want to clarify my question: I have a nested list with an unknown amount of items where some items are not linked. I want to add a class to all unliked items.
推荐答案
仅选择不带锚点的列表项,如问题注释中所述.
Only selecting for list items without anchors, as clarified in the questions comments.
var parentList = $('ul'); // something more specific is assumed.
parentList.children('li').children().not('a').parent().addClass('some-class');
使用包含"使解决方案取决于内容,而不是结构.使用"eq"或类似的"nth"类功能是假设给定的示例是唯一的结构,而我认为它是作为生成的代码进行计划的,该代码可能会扩展到更长的长度,但将始终保持结构中定义的结构.片段.
Using "contains" makes the solution dependent on content, not structure. Using "eq" or similar "nth"-like functionality is assuming that the given example is the only structure, whereas I think it is planned as generated code that may extend to a much longer length, but will always keep the structure defined in the snippet.
这篇关于使用jQuery在嵌套列表中选择所有未链接的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!