jquery - 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>
推荐阅读
- python - 列表元素在 0 元素之后等于 0
- python - Python - 从 SQLite 游标实例化对象
- node.js - 通过 nodemailer 使用 webmail 发送电子邮件
- python - Python中的颜色
- reactjs - 无法将 npm 终端设置为 VS 代码/窗口
- javascript - 从 React js 发送一个 blob 视频文件到烧瓶服务器
- laravel - 为什么路线在 laravel-livewire 中不起作用?
- vba - Visio中的形状动画通过VBA
- java - Java CXF / JAX-WS 可以验证入站 XML 字符编码吗?
- svg - Html中的 SVG 问题