一个相对简单的解决方案,使用一个select
元素来处理语言选择:
$('#language').change(function(){
// storing the language chosen in the select element
var v = this.value;
/* iterates over all li elements, and hides them,
then filters the matched elements to see which elements
contain the relevant language in the 'language' attribute: */
$('ul li').hide().filter(function(i){
return this.getAttribute('language').indexOf(v) !== -1;
// shows the elements that contain the relevant language:
}).show();
});
JS 小提琴演示。
或者稍微不同的方法:
$('#language').change(function () {
var v = this.value;
$('ul li').each(function(){
var l = this.getAttribute('language');
return $(this).toggle(l.indexOf(v) !== -1);
});
});
JS 小提琴演示。
以上两者都适用于以下 HTML:
<label for="language">Show:</label>
<select name="language" id="language">
<option>English</option>
<option>French</option>
<option>German</option>
</select>
<ul>
<li language="English">Australia</li>
<li language="English">America</li>
<li language="French">France</li>
<li language="English French">Canada</li>
<li language="German">Germany</li>
</ul>
顺便提一下,请注意最后一个li
元素中“语言”的更正拼写。
此外,最好更正您的 HTML 以使用有效的(在 HTML5 下)data-*
属性,例如data-language
(使用显而易见的):
<ul>
<li data-language="English">Australia</li>
<li data-language="English">America</li>
<li data-language="French">France</li>
<li data-language="English French">Canada</li>
<li data-language="German">Germany</li>
</ul>
并且修改了上面的代码,以使用修改后的 HTML:
$('#language').change(function(){
// storing the language chosen in the select element
var v = this.value;
/* iterates over all li elements, and hides them,
then filters the matched elements to see which elements
contain the relevant language in the 'language' attribute: */
$('ul li').hide().filter(function(i){
return $(this).data('language').indexOf(v) !== -1;
// shows the elements that contain the relevant language:
}).show();
});
JS 小提琴演示。
$('#language').change(function () {
var v = this.value;
$('ul li').each(function(){
var self = $(this),
l = self.data('language');
return self.toggle(l.indexOf(v) !== -1);
});
});
JS 小提琴演示。
参考: