如何使用Jquery过滤器?

时间:2016-08-22 11:04:02

标签: javascript jquery html

HTML:

<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会填充所有元素作为页面加载但在单个字符之间也无法正常工作。

你能帮我解决一下吗?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

       Ex:
       <ul>
            <li>City 1</li>
            <li>City 2</li>|
            <li>City 3</li>
            <li>City 4</li>
            <li>City 5</li>
        </ul>
a.  .eq(): Get DOM element from specified index. The indexes start from 0
    Ex: $('li').eq(2).css('background-color', 'red');

b.  .first():Gets the first DOM element
    Ex: $('li').first().css('background-color', 'red'); // first index = 0

c.  .last(): Gets the last DOM element
    Ex: $('li').last().css('background-color', 'red'); // first index = 0

d.  .filter():You can filter elements by selecter or by index
    Ex: $('li').filter(':odd').css('background-color', 'red'); //index start from 1.

    //If you want to make the first and fourth elements have a red background then your script would be
   //index start from 0.
        $('li').filter(function(index){
        if(index == 1 || index == 4)
        {
            $(this).css('background-color', 'red');
        }
        });

e.  .has():If you want to check for some condition then the .has() function can be used.
    Ex: $('li').has('a').css('background-color', 'red'); //Check the <a> tag

f.  .not():  If you want to make all the odd items red then your script would look like:
    Ex: $('li').not(':even').css('background-color', 'red'); //index start from 0.