2 hhthwx hhthwx 于 2017.09.18 23:03 提问

document.getELementsById is not a function
js

<!DOCTYPE html>



儒家二级联动
<br> var seljia = document.getELementsById(&quot;jia&quot;);<br> var jiaArr = [&quot;请选择&quot;,&quot;儒家&quot;,&quot;佛家&quot;,&quot;道家&quot;];<br> var exampleArr = [<br> [&quot;请选择&quot;],<br> [&quot;孔子&quot;,&quot;论语&quot;,&quot;三字经&quot;],<br> [&quot;释迦摩尼&quot;,&quot;金刚经&quot;,&quot;冷颜经&quot;],<br> [&quot;老子&quot;,&quot;庄子&quot;,&quot;北斗经&quot;]<br> ];<br> window.onload = function(){<br> // alert(&quot;haha&quot;);</p> <pre><code> seljia.length = jiaArr.length; for(var i = 0;i&lt;jiaArr.length;i++){ seljia.option[i].text = jiaArr[i]; seljia.option[i].value = jiaArr[i]; } function ChangeExampleSelect(index){ var selExa = document.getElementById(&quot;example&quot;); selExa.length = exampleArr[index].length; for(var i =0;i&lt;exampleArr[index].length;i++){ selExa.options[i].text = exampleArr[index][i]; selExa.options[i].value = exampleArr[index][i]; } } } &lt;/script&gt; </code></pre> <p></head><br> <body></p> <!-- 返回当前选项的下表索引值 --> <pre><code>&lt;select id=&quot;jia&quot; onchange=&quot;ChangeExampleSelect(this.selectedIndex)&quot;&gt; &lt;/select&gt; &lt;select id=&quot;example&quot;&gt; &lt;/select&gt; </code></pre> <p></body><br> </html></p>

1个回答

showbo
showbo   Ds   Rxr 2017.09.19 08:34

document.getElementById
不是
document.getELementsById
注意大小写和拼写正确来

而且js放到window.onload里面或者dom对象项目,要不无法找到dom对象,因为从上到下解析,dom还没有生成。ChangeExampleSelect放到onload外,要不dom直接onchange绑定的事件要在window作用域下才能访问到

一堆毛病


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>儒家二级联动</title>
</head>
<body>
    <!-- 返回当前选项的下表索引值 -->
    <select id="jia" onchange="ChangeExampleSelect(this.selectedIndex)"></select>
    <select id="example"></select>

    <script type="text/javascript">
        var seljia = document.getElementById("jia");
        var jiaArr = ["请选择", "儒家", "佛家", "道家"];
        var exampleArr = [
          ["请选择"],
          ["孔子", "论语", "三字经"],
          ["释迦摩尼", "金刚经", "冷颜经"],
          ["老子", "庄子", "北斗经"]
        ];

        function ChangeExampleSelect(index) {
            var selExa = document.getElementById("example");
            selExa.length = exampleArr[index].length;
            for (var i = 0; i < exampleArr[index].length; i++) {
                selExa.options[i].text = exampleArr[index][i];
                selExa.options[i].value = exampleArr[index][i];

            }
        }
        window.onload = function () {

            seljia.length = jiaArr.length;
            for (var i = 0; i < jiaArr.length; i++) {
                // // // // // // // // //options,不是option
                seljia.options[i].text = jiaArr[i];
                seljia.options[i].value = jiaArr[i];
            }
        }
    </script>

</body>
</html>
Csdn user default icon
上传中...
上传图片
插入图片