2012-09-24 29 views
3

選擇菜單我使用此代碼來過濾我<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 = [];並將所有原始值加入它嗎?

回答

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(); 

或像這樣,維持chainability:

var options = $(select).children("option:not(:first)").remove().end().data('options'); 

編輯答案

$(select).children("option").not(":first") 
$(select).find('option').not('option:first-child') 

孩子VS發現:

的.childre n()方法與.find()的不同之處在於.children()只有 沿着DOM樹向下行進,而.find()可以向下遍歷 向下多級選擇後代元素(孫, 等) 。

由於optionsselect元素的直接子元素,所以最好使用children()。

:第一VS:第一胎

的:第一僞類相當於:當量(0)。它也可能是 寫成:lt(1)。雖然這隻匹配一個元素,但第一個孩子可以匹配多個:每個父母一個。

我們只有一位家長(我們的select)。所以在這裏工作。 但是,請注意:

因爲:首先是一個jQuery的擴展,並查詢使用不是CSS 規範的一部分:第一不能利用由本地DOM querySelectorAll提供的 性能提升的() 方法。爲了在使用時達到最佳性能:首先選擇 元素,首先使用純CSS選擇器選擇元素,然後使用.filter(「:first」)(或here,.not(「:first」))

通常情況下,這一切都取決於情況/背景。

+0

'.attr( '相對',option.rel)'完美。將使用:'$(select).children(「option」)。not(「:first」)。remove();'與使用'$(select).find('option')不同。第一個孩子')。each(function(){'? – tcd

+0

@tdun我編輯了我的答案。有些區別,但是在這種情況下效果相同。 – CronosS

+0

太好了,我會再探討一下,非常感謝您的快速響應! – tcd

1

嘗試這樣的屬性:

attr('rel', option.rel) 

無需在$('select').data('option'),因爲你將它們存儲在陣列。使用對象caching,無需換行3次選項即可獲得3個值。

演示怎麼可能是這樣的:http://jsfiddle.net/BSDdZ/

+0

爲了'重新添加'選項'first-child',我在解決方案中使用了部分答案!謝謝! – tcd

+0

@tdun一點都不,祝你有美好的一天;) – webdeveloper