未捕获的TypeError:无法读取未定义的属性'prop' [英] Uncaught TypeError: Cannot read property 'prop' of undefined

查看:209
本文介绍了未捕获的TypeError:无法读取未定义的属性'prop'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有6个输入复选框,如果选中复选框超过3个,则取消选中最后一个复选框。为了更好地理解,请参阅我之前的 问题 即可。哪个已经解决了。

I have 6 input checkboxes and if checkboxes are checked more than 3 the last one gets unchecked. For better understanding refer my previous question. Which is solved.

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

Now, I have another problem, Now 3 checkboxes are checked already by Math.random. On click of any unchecked checkbox. I'm getting error in console.


未捕获的TypeError:无法读取未定义的属性'prop'

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

DEMO FIDDLE

所做的更改

►使用

var checked = $('input[type=checkbox]:checked').map(function(){
 return $(this);
}).get();

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

$(checked.pop()) is used to select the last inserted element.

为什么你的代码无效?

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

As per you code var checked = []; will be empty at the initial stage. So checked[checked.length - 1] will become undefined.

这篇关于未捕获的TypeError:无法读取未定义的属性'prop'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆