试图将连接的JavaScript字符串传递给getElementById?

时间:2016-02-19 20:06:16

标签: javascript

我收到一条错误说:

  

“Uncaught TypeError:无法读取属性'style'的null”

我的JavaScript是:

function AddAFacultyMember(){
    for(x=2;x<=10;x++){

        var str0 = "'";
        var str1 = 'Faculty';
        var str2 = x;
        var str3 = 'input';
        var str4 = "'";

        var concat = str0.concat(str1,str2,str3,str4);

        if( document.getElementById(concat).style.display =='none' ){
            var eligible = concat;
            return;
        }

        document.getElementById(eligible).style.display == 'block';

    }

}

其中一个Faculty div ID的示例是“Faculty1input”。有什么问题?

3 个答案:

答案 0 :(得分:4)

这将有效:

function AddAFacultyMember(){
    for(x=2;x<=10;x++){
        var concat = 'Faculty' + x + 'input';
        var ele = document.getElementById(concat);
        if( ele.style.display =='none' ){
            ele.style.display = 'block';
        }
    }

}

答案 1 :(得分:1)

发现了这个问题!

double ==没有将getElementById(符合条件)的显示重新设置为'block',尽管它正确构造了字符串。溶液/修复:

document.getElementById(eligible).style.display = 'block';

还删除了str0和str4:

function AddAFacultyMember(){
    for(x=2;x<=10;x++){ 
        var str1 = 'Faculty'; 
        var str2 = x; 
        var str3 = 'input'; 
        var concat =str1.concat(str2,str3);

        if( document.getElementById(concat).style.display =='none' ){

            var eligible = concat;
            document.getElementById(eligible).style.display = 'block';
            eligible = '';
            return;
        }

    }

}

感谢大家的帮助!

答案 2 :(得分:0)

试试这个:

función AddAFacultyMember({ 
    for(x=2;x<=10;x++){ 
        var str1 = 'Faculty'; 
        var str2 = x; 
        var str3 = 'input'; 
        var concat =str1.concat(str2,str3);
       ...