選擇菜單我使用此代碼來過濾我<select>
菜單:jQuery的篩選與相對值
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').not('option:first-child').each(function() {
options.push({value: $(this).val(), text: $(this).text(), rel: $(this).attr('rel')});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
正如你所看到的,我用.not('option:first-child')
排除第一<option>
標籤。
我有2個問題與此代碼,它工作正常,但我需要在我的濾波rel
屬性,我要重新添加option:first-child
當我清楚我的文本框中。
我已將rel: $(this).attr('rel')
添加到我的options
數組中,但我不確定如何將其添加回篩選結果?
我可以創建var original = [];
並將所有原始值加入它嗎?
'.attr( '相對',option.rel)'完美。將使用:'$(select).children(「option」)。not(「:first」)。remove();'與使用'$(select).find('option')不同。第一個孩子')。each(function(){'? – tcd
@tdun我編輯了我的答案。有些區別,但是在這種情況下效果相同。 – CronosS
太好了,我會再探討一下,非常感謝您的快速響應! – tcd