【问题标题】:How can I select elements that don't include part of data- attribute value?如何选择不包含部分数据属性值的元素?
【发布时间】:2018-02-23 03:28:16
【问题描述】:

我尝试在 data 属性中隐藏不包含部分文本的元素。 这是一个例子。预期的结果应该是隐藏所有不包含类似于“UK”的键的元素

<input type="text" id="step3LRGender" data-country="UK IT">
<input type="text" id="step3LRAge" data-country="PL IT">
$('[data-country*="UK"]').show();
$('[data-country!*="UK"]').hide();

【问题讨论】:

  • 为什么不用id?
  • 因为我会有几个不同的元素(div、标签、输入)

标签: jquery attributes jquery-selectors


【解决方案1】:

将您的代码与:not() 结合起来,就像$('input:not([data-country*="UK"])').hide(); 一样

演示

$('input[data-country*="UK"]').show();
$('input:not([data-country*="UK"])').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="step3LRGender" data-country="UK IT">
<input type="text" id="step3LRAge" data-country="PL IT">

您还可以使用以下内容:

$('input,div').filter(function() {
  return $(this).data('country').indexOf("UK") > -1 ? $(this).show() : $(this).hide();
});

演示

$('input,div').filter(function() {
  return $(this).data('country').indexOf("UK") > -1 ? $(this).show() : $(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="step3LRGender" data-country="UK IT">
<input type="text" id="step3LRAge" data-country="PL IT">

<div data-country="UK IT">UK IT</div>
<div data-country="PL IT">PL IT</div>

【讨论】:

  • 问题是我需要显示和隐藏不同类型的元素,而不仅仅是输入(对不起,示例中只有输入)
  • @CarlosMartins 尝试运行第二个演示。你可以添加你想要的选择器
猜你喜欢
  • 2018-02-21
  • 2021-02-06
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 2014-08-31
  • 2011-10-10
  • 2021-09-30
  • 1970-01-01
相关资源
最近更新 更多