3

我使用此代码过滤我的<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 = [];并将所有原始值推入其中吗?

4

2 回答 2

1

要在过滤中包含 rel 属性,您几乎完成了这项工作。只需添加.attr('rel', option.rel)

$('<option>').text(option.text).val(option.value).attr('rel', option.rel)

而不是重新添加第一个option,您可以保留它,并删除其他:

$(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')

儿童 VS 发现:

.children() 方法与 .find() 的不同之处在于 .children() 仅沿 DOM 树向下移动一个级别,而 .find() 也可以向下遍历多个级别以选择后代元素(孙子等)。

由于options是元素的直接子select元素,因此最好使用 children()。

:first VS :first-child

:first 伪类等价于 :eq(0)。它也可以写成:lt(1)。虽然这仅匹配一个元素,但 :first-child 可以匹配多个:每个父元素一个。

我们只有一个父母(我们的select)。所以两者都在这里工作。 但是,请注意:

因为 :first 是一个 jQuery 扩展而不是 CSS 规范的一部分,所以使用 :first 的查询不能利用原生 DOM querySelectorAll() 方法提供的性能提升。为了在使用 :first 选择元素时获得最佳性能,首先使用纯 CSS 选择器选择元素,然后使用 .filter(":first") (或此处为 .not(":first"))

通常,这完全取决于情况/上下文。

于 2012-09-24T07:40:00.217 回答
1

尝试这样的属性:

attr('rel', option.rel)

不需要 in $('select').data('option'),因为您将它们存储在数组中。使用 object caching,无需包装 3 次选项即可获得 3 个值。

演示它的样子:http: //jsfiddle.net/BSDdZ/

于 2012-09-24T07:44:44.360 回答