2016-02-28 106 views
0

您好我正在使用jQuery过滤页面上的元素的列表使用HTML选择,其中有一个客户端IDS的列表。页面上的HTML元素的数据属性为data-client。我正在使用jQuery来过滤掉那些不匹配的。但是我的代码隐藏了所有元素。我的代码在下面;jQuery的基于数据属性显示/隐藏多个元素

<select class="form-control placeholder" id="filterSelect" name="clients"> 
    <option value="14">Client 14</option> 
    <option value="45">Client 45</option> 
    <option value="48">Client 48</option> 
</select> 

<div class="filterable"> 
    <div class="filter" data-client="14"> 
    <h3>Hello World</h3> 
    <h4>Client 14</h4> 
    </div> 
    <div class="filter" data-client="45"> 
    <h3>Hello World</h3> 
    <h4>Client 45</h4> 
    </div> 
    <div class="filter" data-client="48"> 
    <h3>Hello World</h3> 
    <h4>Client 48</h4> 
    </div> 
    <div class="filter" data-client="14"> 
    <h3>Hello World</h3> 
    <h4>Client 14</h4> 
    </div> 
    <div class="filter" data-client="48"> 
    <h3>Hello World</h3> 
    <h4>Client 48</h4> 
    </div> 
</div> 

我的jquery如下;

$('#filterSelect').change(function() { 
    var optionSelected = $("option:selected", this).val(); 
    var filter = $('.filter'); 

    if (filter.attr('data-client') != optionSelected) { 
    filter.hide(); 
    } 

}); 

我也有一个jsfiddle;

https://jsfiddle.net/to53jbe5/

希望有人可以帮我过滤掉不选择的选择值相匹配的人。

回答

6

使用[data-client="YOUR_VALUE"]来选择具有属性的元素。 $('.filter[data-client="' + optionSelected + '"]')将选择具有类别filter和属性data-client的所有元素作为选定的值。 [Reference]

.change()将触发事件change最初筛选选择的值的元素

尝试这种情况:

$('#filterSelect').change(function() { 
 
    var optionSelected = $("option:selected", this).val(); 
 
    $('.filter').hide(); 
 
    $('.filter[data-client="' + optionSelected + '"]').show(); 
 
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<select class="form-control placeholder" id="filterSelect" name="clients"> 
 
    <option value="14">Client 14</option> 
 
    <option value="45">Client 45</option> 
 
    <option value="48">Client 48</option> 
 
</select> 
 

 
<div class="filterable"> 
 
    <div class="filter" data-client="14"> 
 
    <h3>Hello World</h3> 
 
    <h4>Client 14</h4> 
 
    </div> 
 
    <div class="filter" data-client="45"> 
 
    <h3>Hello World</h3> 
 
    <h4>Client 45</h4> 
 
    </div> 
 
    <div class="filter" data-client="48"> 
 
    <h3>Hello World</h3> 
 
    <h4>Client 48</h4> 
 
    </div> 
 
    <div class="filter" data-client="14"> 
 
    <h3>Hello World</h3> 
 
    <h4>Client 14</h4> 
 
    </div> 
 
    <div class="filter" data-client="48"> 
 
    <h3>Hello World</h3> 
 
    <h4>Client 48</h4> 
 
    </div> 
 
</div>

Fiddle here