1

I have a function that gets the id's of all the checked and unchecked checkboxes then hides or shows the element depending if it's checked or not. My problem is that I'm getting:

TypeError: upperPos[this] is undefined upperPos[this].hide();

but Im not getting this error on upperPos[this].show(); (and the elements appear as they should)

jquery:

$('body').on('change', '.optionForm', function() {
    var formId      = $(this).attr('id'),
        checked     = new Array();
        unchecked   = new Array();
    $('#' + formId + ' input:checked').each(function() {
        checked.push($(this).attr('id'));
    });
    $('#' + formId + ' input:not(:checked)').each(function() {
        unchecked.push($(this).attr('id'));
    });
    console.log(checked);
    $.each(checked, function() {
        upperPos[this].show();/*This does not have an error*/
    });
    console.log(unchecked);
    $.each(unchecked, function() {
        upperPos[this].hide();/*This is error*/
    });
});

Both arrays are being populated correctly.

upperPos[] contains an array of raphael objects. The id's of the checkboxes correspond to the raphael objects and the function is supposed to hide/show them accordingly.

I would appreciate any help on why Im getting this error. If you need any additional info, please let me know.

Thanks, Adam

jsFiddle: http://jsfiddle.net/adam123/Jw9h5/60/

For some reason the fiddle works, but my code does not.

4

2 回答 2

1

这很简单意味着该对象不存在于 upperPos数组中。

soupperPos[this]对于数组中的特定项目是未定义的。而且您不应该在this这里使用,因为已检查未检查的数组是字符串数组。

尝试这个

$.each(checked, function(i, val) {
   upperPos[val] && upperPos[val].show();
});
console.log(unchecked);

$.each(unchecked, function(i, val) {
   upperPos[val] && upperPos[val].hide();
});
于 2013-06-19T00:56:31.980 回答
0

可以建议你改成这个吗?除非您需要其他数组,否则请告诉我,我会编辑:

$('body').on('change', '.optionForm', function() {
    var formId      = $(this).attr('id'),

    $('#' + formId + ' input:checked').each(function() {        
        $(this).show();
    });
    $('#' + formId + ' input:not(:checked)').each(function() {
            $(this).hide();
    });

});
于 2013-06-19T00:35:37.147 回答