简体   繁体   English

document.getelementById在动态生成的div上不起作用

[英]document.getelementById doesn't work on dynamically generated divs

I am trying to update the content of a dynamically generated div with .innerHTML and getElementById, but when I test it, I get an error: "Uncaught TypeError: Cannot set property 'innerHTML' of null" I also tried using alert() and checking the value of quizDiv at breakpoints. 我正在尝试使用.innerHTML和getElementById更新动态生成的div的内容,但是当我对其进行测试时,出现了一个错误:“ Uncaught TypeError:无法将属性'innerHTML'设置为null”我也尝试使用alert()和在断点处检查quizDiv的值。 Well, here's my JS file called main.js: 好吧,这是我的JS文件,名为main.js:

function makeDiv() {
document.body.innerHTML = "<div id='quizDiv'></div>"
}
function createInputBox(boxId) {
     var quizDiv = document.getElementById("quizDiv");
     quizDiv.innerHTML = "<input type='text' id='" + boxId + "'>";
 }
makeDiv();
createInputBox(1);

Here's my html: 这是我的html:

<!-- doctype, head, etc -->
<body>
<!-- content -->
<script src="/main.js"></script>
</body>

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

Since you already creating the div in js, why not hold the reference then? 既然您已经在js中创建了div,那么为什么不保存引用呢?

function makeDiv() {
    var quizDiv=document.createElement("div");
    document.body.appendChild(quizDiv);
    return quizDiv;
}
function createInputBox(quizDiv,boxId) {
     // var quizDiv = document.getElementById("quizDiv");
     quizDiv.innerHTML = "<input type='text' id='" + boxId + "'>";
 }
var quizDiv=makeDiv();
createInputBox(quizDiv,1);

There are a few problems with you code. 您的代码有一些问题。

Firstly the HTML is not valid, meaning ID's can't start with numbers. 首先,HTML无效,这意味着ID不能以数字开头。 Read more about how to overcome this issue here: CSS-Tricks 在此处阅读有关如何克服此问题的更多信息: CSS-Tricks

Secondly, you code 'works' could you provide an image of your directory structure and the full markup? 其次,您编码为“作品”,是否可以提供您的目录结构和完整标记的图像? Here is a jsfiddle with your code and it displays the input: jsFiddle Maybe there is a problem with the file path or your calling the js file before the document is ready. 这是一个包含代码的jsfiddle,它显示输入: jsFiddle也许文件路径有问题,或者您在准备好文档之前调用js文件。

I cleaned your code up a bit so maybe try this instead: 我整理了一下您的代码,所以也许试试看:

window.onload = function () {

    var body = document.body;

    function createDiv (identifier) {
        var el = document.createElement('div');
        el.id = identifier;

        body.appendChild(el);
    }

    function createInput(identifier) {
        var div = document.getElementById('quizDiv');
        div.innerHTML = "<input type='text' id='" + identifier + "'>";
    }

    createDiv('quizDiv');
    createInput('bar');
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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