我使用此代码来过滤我的 <select>
菜单:
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>
标签。
这段代码有两个问题,它工作正常,但我需要包含 rel
我的过滤中的属性,我想重新添加 option:first-child
当我清除文本框时。
我添加了rel: $(this).attr('rel')
给我的options
数组,但我不确定如何将其添加回过滤结果中?
我可以创建 var original = [];
并将所有原始值插入其中?
最佳答案
要在过滤中包含 rel 属性,您几乎完成了这项工作。只需添加 .attr('rel', option.rel)
:
$('<option>').text(option.text).val(option.value).attr('rel', option.rel)
您可以保留它,然后删除其他选项,而不是重新添加第一个选项
:
$(select).children("option").not(":first").remove();
编辑(如何检索“数据”属性):
您可以这样做(可使用变量缓存进行改进):
var options = $(select).data('options');
$(select).children("option").not(":first").remove();
或者像这样,保持可链接性:
var options = $(select).children("option:not(:first)").remove().end().data('options');
已编辑答案
$(select).children("option").not(":first")
$(select).find('option').not('option:first-child')
child VS查找:
The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.
由于options
是select
元素的直接子元素,所以最好使用children()。
:第一个 VS :第一个 child
The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.
我们只有一个父级(我们的select
)。所以两人都在这里工作。
但是请注意:
Because :first is a jQuery extension and not part of the CSS specification, queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first") (or here, .not(":first")).
通常,这完全取决于情况/背景。
关于带有 rel 值的 jQuery 过滤器选择菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12559845/