我需要为 <ul>
应用一个类只有当它有一个 <li>
只包含一个 child 应该是 <strong>
& 没有别的(在 <strong>
之前或之后没有文本节点或其他元素。
我在这里提到了多个帖子,它们解决了上述问题的不同部分。我已经编写了以下代码。但是,它正在将类添加到所有 <ul>
& 过滤条件未被应用。
$('ul.list-style').filter(function(){
return $(this).children("li")
.filter(function(){ return $(this).contents()
.filter(function() { return this.nodeType == Node.ELEMENT_NODE || (this.nodeType == Node.TEXT_NODE && !!$.trim(this.nodeValue)) }).length=1 })
.filter(function(){ return $(this).children("strong").length = 1 }).length = 1 })
.addClass("only-strong");
最佳答案
备选方案 - 单一过滤器 - 我相信它有效
$('ul.list-style > li:only-child > strong:only-child').filter(function() {
return !this.nextSibling;
}).parent().parent('ul.list-style').addClass('only-strong');
.only-strong {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class='list-style'>
<li><strong>Must be RED</strong></li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class='list-style'>
<li>Also must be <strong>RED</strong></li>
</ul>
<ul class='list-style'>
<li>Can't be <strong>Red</strong> with text outside of strong</li>
</ul>
<ul class='list-style'>
<li><strong>Should not be red</strong></li>
<li>has two li's</li>
</ul>
<ul class='list-style'>
<li><strong>Not red</strong> something after strong</li>
<li><strong>and has two li's</strong></li>
</ul>
<ul class='list-style'>
<li><strong>NOT RED </strong><span>there's a span here</span></li>
</ul>
关于
的注释return !this.nextSibling;
这意味着 strong
是 li
中的最后一个节点,但是你可以在它之前有文本节点......如果它需要是ONLY li
return !(this.nextSibling || this.previousSibling);
甚至
return this.nextSibling === this.previousSibling;
因为只有当两者都为 null
关于javascript - 如何使用嵌套过滤器来检测是否只有一个 li & 它的 child 只有 <strong>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58517634/