Javascript只有在HTML文档内才能工作。
Javascript只有在HTML文档内才能工作。
这个问题已经有了答案:
我一直在尝试使用数组填充下拉列表,我从这篇文章得到了这个例子:JavaScript - populate drop down list with array
我在使用这个HTML:
使用以下js:
var select = document.getElementById("selectNumber"); var options = ["1", "2", "3", "4", "5"]; for(var i = 0; i < options.length; i++) { var opt = options[i]; var el = document.createElement("option"); el.textContent = opt; el.value = opt; select.appendChild(el); }
但它只有在我把js放在HTML文档中时才有效,如果我将它放在一个单独的文件中,它会在Chrome中给我这个错误:
>Uncaught TypeError: Cannot read property 'appendChild' of null at g.js:8
我也尝试过下面的代码,但发生了同样的事情:
var select = document.getElementById("selectNumber"); var options = ["1", "2", "3", "4", "5"]; for(var i = 0; i < options.length; i++) { var opt = options[i]; var el = document.createElement("option"); el.text = opt; el.value = opt; select.add(el); }
只有当我将代码放在HTML文件中时,它才有效,但如果我将其放在单独的文件中,它会给我这个错误。
有什么想法吗?
admin 更改状态以发布 2023年5月21日