//bind an event handler to the text input for the keyup event (so the value will have changed by the time this event fires)
$('input[type="text"]').on('keyup', function (event) {
//convert the value of the text box to lowercase
this.value = this.value.toLowerCase();
//cache the elements that match the search
var good_to_go = $('[data-imgName*=' + $(this).val() + ']').show();
//hide all the elements that do not match the search
$('[data-imgName]').not(good_to_go).hide();
});
有可能是一個辦法做到這一點,執行得更好,但是這需要文字輸入的值,並認爲所有包含文本輸入的值data-imgName
屬性的元素。然後它找到所有具有data-imgName
屬性的元素,並隱藏所有尚未找到的元素。
如果你有一個父元素的所有搜索元素,你應該開始都用它來選擇,以避免搜索整個DOM:
var $container = $('#container-id');
$('input[type="text"]').on('keyup', function (event) {
this.value = this.value.toLowerCase();
if (this.value == '') {
$container.children().show();
} else {
var good_to_go = $container.find('[data-imgName*="' + this.value + '"]').show();
$container.find('[data-imgName]').not(good_to_go).hide();
}
});
注意,這個例子還檢查的價值文本框是什麼都沒有,如果是的話,它顯示所有搜索到的元素。
這裏是爲*=
(含)選擇文檔:http://api.jquery.com/attribute-contains-selector/
這裏是爲.not()
函數文檔:http://api.jquery.com/not
這裏是一個工作演示:http://jsfiddle.net/HRjHV/3/
你可以使用正則表達式,當然,但由於它只是基本字符和字符串的開始,爲什麼不使用函數來查看是否使用了條g從定義的字符開始? – fge 2012-01-13 23:39:12
你需要正則表達式還是僅僅爲了尋找完全匹配而已? – Yogu 2012-01-13 23:40:05
hi @fge。正則表達式,使「bc」隱藏「xyz」,而不是「abc2」 – Kyle 2012-01-13 23:41:27