我尝试根据所选选项创建一个显示 li 元素的过滤器。它有效,当我只选择一个选项时,元素在选择时显示,在取消选择时消失。
But when multiple option are selected, the elements first appear and then disappear again. 我猜循环中的某些东西是错误的?
Javascript:
$(document).ready(function() {
//Hide all li-Elements
$(".result li").hide();
//When select-Element is change, do something
$("select").change(function() {
//Create array for selected Options
var arr = new Array;
//Add all selected Options to the array
$("select option:selected").each(function() {
arr.push($(this).val());
});
//Create a Loop to display li-Elements
for (var i = 0, l = arr.length; i < l; i++) {
/*slideDown all elements which contain one
of the selected elements in array*/
$("li:contains(" + arr[i] + ")").slideDown("slow");
/*slideUp all elements which do not contain
the selected elements in array*/
$('li:not(:contains(' + arr[i] + '))').slideUp("slow");
}
});
});
html:
<select multiple>
<option value="volvo">volvo</option>
<option value="saab">saab</option>
<option value="opel">opel</option>
<option value="audi">audi</option>
</select>
<div class="result">
<ul>
<li>volvo</li>
<li>volvo coolio</li>
<li>saab</li>
<li>opel</li>
<li>opelino</li>
<li>opel meier</li>
<li>audi</li>
</ul>
</div>