2016-08-22 36 views
2

HTML:如何使用Jquery過濾器?

<div class="searchChkBoxDiv"><input id="searchchk_input"></div> 
<div class="searchElemDiv"></div> 

JS:

var checkBoxVals = ["sandeep", "suresh", "rajesh", "ramesh", "pad"]; 
for(var i = 0; i<checkBoxVals.length; i++){ 
      $('.searchElemDiv').append('<div id='+checkBoxVals[i]+'><input type="checkbox"><span>'+checkBoxVals[i]+'</span></div>'); 
      } 

我有上述代碼中,我想以過濾由Java腳本加入searchElemDiv的元素。

我嘗試如下,但未能捕獲過濾器數組中的元素。

$('#searchchk_input').keyup(function(){ 
     var val = $(this).val(); 
     $('.searchElemDiv').empty(); 
     var opt = checkBoxVals.filter(function(idx, el) { 
      return val === '' || el.indexOf(val) == 0; 
      }); 
     for(var i=0; i<opt.length; i++){ 
      $('.searchElemDiv').append('<div id='+opt[i]+'><input type="checkbox"><span>'+opt[i]+'</span></div>'); 
      } 
     }); 

當我把它從searchElemDiv DIV移除所有元素的第一關鍵,當刪除輸入框中再次searchElemDiv充滿了所有的元素,頁面加載,但在單個字符之間的整個輸入也不能正常工作。

你能幫我解決一下嗎?

+0

'checkBoxVals'不是'jQuery-object' – Rayon

+0

http://stackoverflow.com/a/14274386/3986045 我跟着上面的答案在選擇框中實現搜索。 並試圖在div元素中執行搜索。 –

+0

謝謝你們幫助我。 我改變上面的代碼作爲 VAR選擇= checkBoxVals.filter(功能(元件,索引){ \t返回VAL === '' || element.indexOf(VAL)== 0; }); 現在它工作正常。 謝謝@Quentin羅傑。 –

回答

0

的回調過濾器返回三個參數:

// the first is for the value the second for the index 
function callbackfn(value, index, array1) 

到這裏看看:

https://msdn.microsoft.com/en-us/library/ff679973(v=vs.94).aspx

一個小例子:

var checkBoxVals = ["sandeep", "suresh", "rajesh", "ramesh", "pad"]; 
 

 
var opt = checkBoxVals.filter(function(el, idx, array) { 
 
    console.log("index :"+idx); 
 
    console.log("element :"+el); 
 
    console.log("the full array :"+array); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

謝謝,我想我互換地使用了索引和元素。 我改性等 \t \t \t變種選擇= checkBoxVals.filter(功能(IDX,EL){ \t \t \t \t返回VAL === '' || idx.indexOf(VAL)== 0; \t \t \t \t}); 現在它工作正常。 –

+0

樂於助人,歡迎來到SO。如果此答案或任何其他人解決了您的問題,請將其標記爲已接受。 –