gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'prop' of undefined

转载 作者:搜寻专家 更新时间:2023-10-31 22:58:26 25 4
gpt4 key购买 nike

我有 6 个输入复选框,如果选中的复选框超过 3 个,最后一个复选框将被取消选中。为了更好地理解,请引用我之前的 question 。哪个解决了。

现在,我有另一个问题,现在 Math.random 已经选中了 3 个复选框.单击任何未选中的复选框。我在控制台中遇到错误。

Uncaught TypeError: Cannot read property 'prop' of undefined

Fiddle Demo

代码如下:

var random_checked = $("input[type=checkbox]").get().sort(function(){ 
return Math.round(Math.random())-0.6; //so we get the right +/- combo
}).slice(0,3);
$(random_checked).prop('checked', true);



var checked = [];
$('input[type=checkbox]').change(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
checked[checked.length - 1].prop('checked', false);
checked.pop();
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
}
});

最佳答案

你可以试试下面的代码

var checked = $('input[type=checkbox]:checked').map(function(){
return $(this);
}).get(); // First change
$('input[type=checkbox]').change(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
$(checked.pop()).prop('checked', false);// Second change
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
}
});

DEMO FIDDLE

所做的更改

► 使用

将当前选中的元素存储到数组中
var checked = $('input[type=checkbox]:checked').map(function(){
return $(this);
}).get();

$(checked.pop()) 用于选择最后插入的元素。

为什么您的代码不起作用?

根据您的代码,var checked = []; 在初始阶段将为空。所以 checked[checked.length - 1] 将变为未定义。

关于javascript - 未捕获的类型错误 : Cannot read property 'prop' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36500583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com