将 CSS 应用于与数据属性不匹配的元素

Apply CSS to elements that do not match the data attribute

我正在尝试创建一种过滤器。

当用户单击一个按钮时,它将获取该按钮的 ID,并将 display:none; 应用到所有与给定的 data 属性不匹配的元素。

HTML:

<div class="job-list">
    <div class="row">
        <div class="grid half">
            <div class="job-item" data-job-type="fulltime">
                <h3>Marketing &amp; Communications Manager</h3>
                <h4>Central London -  salary competitive</h4>
            </div>
        </div>

       <div class="grid half">
           <div class="job-item" data-job-type="parttime">
               <h3>Senior PR &amp; Media Manager</h3>
               <h4>Central London -  salary dependent on experience</h4>
           </div>
       </div>
   </div>

当用户点击按钮时,变量 selection 被设置为 parttimefulltime

var selection = 'fulltime';

然后我尝试匹配页面上的元素:

a) .job-list

b) 有 data-job-type="[the selection var set above]"

$('.job-list div[data-job-type!="'+selection+'"]').css('display','none'); 

但是我发现它选择了整个 .job-list 并将 display:none; 应用于它,而不是匹配的子元素?

JSFiddle https://jsfiddle.net/h9s3szg2/

根据 documentation

Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

您的选择器过于激进。它正在选择所有 div,即使它们没有属性,因为它们满足条件 [data-job-type!="'+selection+'"]。向选择器添加一个额外的 [data-job-type] 以仅针对具有该属性的 div

$(document).ready(function() {
  $('.button').click(function() {
    var selection = 'fulltime';
    $('.job-list div[data-job-type][data-job-type!="' + selection + '"]').closest('.grid').hide();
  });
});
.job-item {
  width: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="button">Click me!</div>
<div class="job-list">
  <div class="row">
    <div class="grid half">
      <div class="job-item" data-job-type="fulltime">
        <h3>Marketing &amp; Communications Manager</h3>

        <h4>Central London -  salary competitive</h4>

      </div>
    </div>
    <div class="grid half">
      <div class="job-item" data-job-type="parttime">
        <h3>Senior PR &amp; Media Manager</h3>

        <h4>Central London -  salary dependent on experience</h4>

      </div>
    </div>
  </div>
</div>

一些旁注。

  1. hide()可以用来代替css('display', 'none')
  2. 最好hide()整体子容器,本例grid