[英]Getting value of a “object HTMLInputElement” and function error
I have checkboxes on a page and I get the checked ones then I loop through them; 我在页面上有复选框,选中了这些复选框,然后循环浏览它们;
var checkeds = $('#accTypes input:checked');
var values = "";
for (var i = 0; i < checkeds.length; i++) {
console.log(checkeds[i]);
var cval = checkeds[i].val();
values = values + "," + cval;
}
I recognized that the row below causes error. 我认识到下面的行会导致错误。
checkeds[i].val()
When I print the checkeds[i] variable in chrome console, I see; 当我在chrome控制台中打印checkeds [i]变量时,我看到了;
<input type="checkbox" name="accom-check" id="checkboxP12" value="12">
I wanted to get the value of checkeds[i] variable. 我想获取checkeds [i]变量的值。 How can I do this? 我怎样才能做到这一点?
A jQuery collection is an array-like object containing native DOM nodes. jQuery集合是包含本地DOM节点的类似数组的对象。
When you access it as checkeds[1]
you get the native DOM node, not the jQuery version, so it doesn't have a val()
method. 当您以checkeds[1]
身份访问它时,您将获得本机DOM节点,而不是jQuery版本,因此它没有val()
方法。
Either use the native value 要么使用本机值
var cval = checkeds[i].value;
or use eq()
to get the jQuery object 或使用eq()
获取jQuery对象
var cval = checkeds.eq(i).val();
As a sidenote, you could do the same thing with a map 作为旁注,您可以对地图执行相同的操作
var values = $('#accTypes input:checked').map(function() {
return this.value;
}).get().join(',');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.