javascript - 如何使用嵌套过滤器来检测是否只有一个 li & 它的 child 只有 <strong>

标签 javascript jquery

我需要为 <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;

这意味着 strongli 中的最后一个节点,但是你可以在它之前有文本节点......如果它需要是ONLY li

中的节点
return !(this.nextSibling || this.previousSibling);

甚至

return this.nextSibling === this.previousSibling;

因为只有当两者都为 null

时才为真

关于javascript - 如何使用嵌套过滤器来检测是否只有一个 li & 它的 child 只有 <strong>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58517634/

相关文章:

javascript - anchor 链接在 Accordion 效果的替代选项卡内不起作用

javascript - 在 C3 Js 图表中首次加载页面时启用/禁用图例元素。此外,管理图例元素根据复选框值启用/禁用

javascript - 回调函数数组

javascript - 当做出选择框选项时,如何停止隐藏页面上所有 div 的 JS 查询?

javascript - 使用 MooTools/jQuery 的 Ajax 问题 - p.onStatusChange 不是函数

javascript - 使用 es6 或 lodash 将字符串数组转换为对象数组

javascript - Vuex 存储在 vue-router 中未定义

javascript - 为什么这会连接而不是相加

javascript - getJSON : how to try to get some url until success in every 0. 5 秒?

javascript - 雅虎财经 Api 不返回值