如何使用jquery检查一些数字是否包含在逗号分隔的数字中?

时间:2015-05-20 01:14:04

标签: jquery filter

当使用jquery点击按钮时,如何仅显示编号与var内部数字匹配的li项目,使用jquery?

var numbers = "1,2,3,4,5,300"; 

HTML

  <ul>
     <li>1</li> <!-- should be seen on click-->
     <li>7</li> <!-- should not be seen on click-->
     <li>3</li> <!-- should be seen on click-->
     <li>9</li> <!-- should not be seen on click-->
  </ul>
  <button id="filter">Click me</button> 

编辑:var中的数字是逗号分隔数字

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
// it would be better to start with an array, but if you have to start with a string
var string = "1,2,3,4,5,300";
// use .split to convert it to an array of strings
var toInclude = string.split(",");

$(function() {
  // select all your li elements
  // if you have more ul elements on the page with more li's you might
  // want a more specific selector using a class and/or an id
  $("ul li").each(function(li) {          // loop through them using each
    var num = $(this).text();             // get the text in each element
    if (toInclude.indexOf(num) == -1) {   // check the array to see if there's a match
      $(this).hide();                     // if no match, hide it.
    }
  });

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <!-- should be seen on click-->
  <li>7</li>
  <!-- should not be seen on click-->
  <li>3</li>
  <!-- should be seen on click-->
  <li>9</li>
  <!-- should not be seen on click-->
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

小提琴escaping directive

您需要做的就是遍历li标记并对每个innerHTML进行数组查找。如果不存在,请隐藏它。

var numbers = [1,2];

$("li").each(function() {
    var text = parseInt(this.innerHTML), inArray = false;
    for(var i = 0, len = numbers.length; i < len; i++) {
        if(numbers[i] === text) {
            inArray = true;
        }
    }
    if(!inArray) {
        $(this).hide()
    }

});

答案 2 :(得分:0)

没有JQuery的解决方案:

<html>
<body>
    <script>
function onClickHandler() {
    var numString = "1,2,3,4,5,300",
        nums = numString.split(","),
        ul = document.getElementById("list"),
        items = ul.getElementsByTagName("li");
    for (var i = 0; i < items.length; ++i) {
        if (nums.indexOf(items[i].innerHTML) == -1) {
            items[i].style.display = "none";
        }
    }
}
    </script>
    <ul id="list">
        <li>1</li> <!-- should be seen on click-->
        <li>7</li> <!-- should not be seen on click-->
        <li>3</li> <!-- should be seen on click-->
        <li>9</li> <!-- should not be seen on click-->
    </ul>
    <button id="filter" onclick="onClickHandler();">Click me</button> 
</body>
</html>