2016-02-28 108 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