提问者:小点点

带有dataset的jQuery元素


我想根据元素的数据集过滤元素。我创建了一个小提琴来显示我所处的位置:这里,但如你所见,当我选择“红色”时,它只是隐藏了“红色”项,而不是其他项。就像“黄色”一样,它不会做任何事情。

下面是脚本:

// Filter by color
$(document).on('change', 'input', function(){
  const color_value = this.value;
  let $products = $('li').hide();
  let $filtered = $products.filter((i, el) => el.dataset.color !== '' && el.dataset.color.indexOf(`-${color_value}-`));
  $filtered.show();
});

多谢!


共1个答案

匿名用户

您可以使用indexof()代替include()

更改:

el.dataset.color.indexOf(`-${color_value}-`)

致:

el.dataset.color.includes(`-${color_value}-`)

null

$(document).on('change', 'input', function(){
  const color_value = this.value;
  let $products = $('li').hide();
  let $filtered = $products.filter((i, el) => el.dataset.color !== '' && el.dataset.color.includes(`-${color_value}-`));
  $filtered.show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" value="red" id="red" name="color">
<label for="red">Red</label>
<input type="radio" value="blue" id="blue" name="color">
<label for="blue">Blue</label>
<input type="radio" value="purple" id="purple" name="color">
<label for="purple">purple</label>
<input type="radio" value="yellow" id="yellow" name="color">
<label for="yellow">yellow</label>

<ul>
  <li data-color="-red--yellow-">
    Red and yellow thing
  </li>
  <li data-color="-blue-">
    Blue thing
  </li>
  <li data-color="-purple--red-">
    Purple and red thing
  </li>
</ul>