简体   繁体   中英

why i can't use xx[this.index].style.display? it's said “Cannot read property 'style' of undefinedbtn”

i want to make xx[this.index] in a loop for making each one has an index and then when i click a button of them, the background of button would turn to yellow color & the div block would change the words at the same time. why it doesn't work? i saw other people use this way is working good. how can I do? thanks a lot!

here is my JSFiddle: http://jsfiddle.net/QCxwr/7

 window.onload=function()
    {
        var btn = document.getElementsByTagName('input');
        var div = document.getElementsByName('div');

        for(var i=0;i<btn.length;i++) {
            btn[i].index = i;
            btn[i].onclick=function() {
                for(var i=0;i<btn.length;i++) {
                    btn[i].className = '';
                    div[i].style.display='none';
                }
                this.className = 'active';
                div[this.index].style.display = 'block';
            };
        }
    };

this will refer to the window here. Unless you put a property index on the object window (really not advised) this won't work.

So if this function is executed in a method on a object you'll have to do the classic trick :

 var me = this;
 window.onload=function(){
     ...
     div[me.index].style.display = 'block';
 }

Your DIV array is empty. Did you mean to use

getElementsByTagName

instead of

getElementsByName

when returning the DIVs?

Also You should check the array length before attempting to access.

Updated code http://jsfiddle.net/QCxwr/9/

Please find the updated javascript code. Your DIVs array is 0 as you fetch using "getElementsByName".

window.onload=function()
        {
            var btn = document.getElementsByTagName('input');
            var div = document.getElementsByTagName('div');

            for(var i=0;i<btn.length;i++) {
                btn[i].index = i;alert
                btn[i].onclick=function() {                
                    for(var i=0;i<btn.length;i++) {
                        btn[i].className = '';
                        div[i].style.display='none';
                    }
                    this.className = 'active'; 
                    div[this.index].style.display = 'block';
                };
            }
        };

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