首页 > 解决方案 > jQuery inArray 使用 -1 匹配错误的值

问题描述

我有一个值为 -1、1、2、3、4 等的数组。我使用此代码查看复选框的值是否在数组中:

jQuery("#checkbox-container").find("input[type=\'checkbox\']").each(function() {
    var state = jQuery.inArray(this.value, targetarray)!=-1;
         
    jQuery(this).prop("checked", state);
});

它适用于除-1之外的所有数字。它将选择值为 1 而不是 -1 的复选框。为什么这样做?

标签: jquerycheckbox

解决方案


我使用 parseInt() 将字符串转换为 int。如果 targetarray 以 int 数组的形式给出,但 this.value 是一个字符串。

<html>
<head>
  <meta charset="UTF-8">
  <script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    var targetarray = [-1, 1, 2, 3, 4];
    $(document).ready(function() {
      jQuery("#checkbox-container").find("input[type=\'checkbox\']").each(function() {
        var state = jQuery.inArray(parseInt(this.value), targetarray)!=-1;
        
        jQuery(this).prop("checked", state);
      });
    });
  </script>
</head>

<body>

<div id="checkbox-container">
<input type="checkbox" value="-1">-1</input>
<input type="checkbox" value="0">0</input>
<input type="checkbox" value="1">1</input>
<input type="checkbox" value="2">2</input>
<input type="checkbox" value="3">3</input>
<input type="checkbox" value="4">4</input>
<input type="checkbox" value="5">5</input>
</div>

</body>
</html>


推荐阅读