简体   繁体   中英

Undefined var in IE8 javascript/jQuery

I'm having a bit of an issue with IE8 and jQuery 1.9.1.

The target browser is IE8. I get an undefined variable when I try to alert the rolevalue var.

Here's the code:

function get_role(){
    var test = document.getElementsByName("admin_role");
    for(var elem in test){
        if(test[elem].checked){
            var rolevalue = test[elem].value;
            $.post('<?php echo base_url(); ?>ajaxsc/getrole/',{role:rolevalue},function(result){
                $('#roletest').html(result);
                });
        }
    }
    **alert('role = ' + rolevalue);**
    return rolevalue;
}

The problem is that the for..in loop is iterating over some unwanted items.

If you using a for..in loop, you need to be aware of this; you may get the loop iterating over object properties that are part of the object prototype rather than actual elements that you want to iterator over.

What is happening is that it's hitting an property in the loop that is not a DOM element, and of course, that means it doesn't have a .value , so when you try to set the variable from .value , you get undefined .

To avoid this, you need to use the .hasOwnProperty() method to determine whether the loop is iterating a prototype method, and avoid them. You need to do something like this:

for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
        .....
    }
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM