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的复选框。它为什么这么做?

我使用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>

最新更新