使用jQuery检查标题的可见项-需要不同的方法

问题描述

使用jQuery时,我需要检查该标题是否有可见的列表项
下面是我的方法,基本上是通过字符串将类名串联起来来检查具有相同类名的li元素。 由于以下原因,此方法不起作用:

当我使用

let captionClass = $(caption).attr('class');

一旦我有带有特殊字符的选择器,脚本就会失败,在此示例中为'&'

我尝试使用 jQuery.escapeSelector()函数

let captionClass = $.escapeSelector($(caption).attr('class'));

但这似乎不起作用,因为我们使用的是Magento 2.3随附的旧版jQuery版本,我无法更改。

我现在可以尝试自己逃脱角色,例如:
Need to escape a special character in a jQuery selector string

但是所有这些使我怀疑我的整个方法。 也许jQuery提供了更简单的解决方案?

实现我最初的目标最简单,最干净的方法是什么?

检查每个标题是否有可见项目。

我无法更改jQuery版本,也不能更改其中包含特殊字符的类名称
其余的几乎所有内容都可以调整,包括html结构。

无论如何,这是我的方法代码

$('h4').each((index,caption) => {
    console.log(caption);
    console.log($(caption).attr('class'));
    console.log('li.product.'+$(caption).attr('class')+':visible');
    let captionClass = $.escapeSelector($(caption).attr('class'));
    //let captionClass = $(caption).attr('class'); 
    console.log(captionClass);
    if ($('li.product.'+captionClass+':visible').length === 0) {
        $(caption).hide();
    } else {
        $(caption).show();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<ul id="product-list">
    <h4 class="color-red">Red</h4>
    <li class="product color-red size-l">Red Large</li>
    <li class="product color-red size-m">Red Medium</li>
    <li class="product color-red size-s">Red Small</li>
    <h4 class="color-blue">Blue</h4>
    <li class="product color-blue size-l">Blue Large</li>
    <li class="product color-blue size-m">Blue Medium</li>
    <li class="product color-blue size-s">Blue Small</li>
    <h4 class="color-&-white">White</h4>
    <li class="product color-&-white size-l">White Large</li>
    <li class="product color-&-white size-m">White Medium</li>
    <li class="product color-&-white size-s">White Small</li>
</ul>

解决方法

我现在这样解决了:

  1. 查询所有可见的li.product
  2. filter()h4类别相同的项目的结果

还可以尝试摆脱类名中的无效字符,但这是另一个主题。

$(document).ready(function() {
  $('h4').each((index,caption) => {
      if ($('li.product:visible').filter((i,e) => {
          return $(e).hasClass($(caption).attr('class'));
      }).length === 0) {
          $(caption).hide();
      } else {
          $(caption).show();
      }
  });
});
.color-red {
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<ul id="product-list">
    <h4 class="color-red">Red</h4>
    <li class="product color-red size-l">Red Large</li>
    <li class="product color-red size-m">Red Medium</li>
    <li class="product color-red size-s">Red Small</li>
    <h4 class="color-blue">Blue</h4>
    <li class="product color-blue size-l">Blue Large</li>
    <li class="product color-blue size-m">Blue Medium</li>
    <li class="product color-blue size-s">Blue Small</li>
    <h4 class="color-&-white">White</h4>
    <li class="product color-&-white size-l">White Large</li>
    <li class="product color-&-white size-m">White Medium</li>
    <li class="product color-&-white size-s">White Small</li>
</ul>