首页 > 解决方案 > Javascript getElementById 未定义

问题描述

我想单击添加按钮将新<p>元素插入<div id="output">. 当我单击删除按钮时,它应该删除<p>我刚刚附加到 div 输出中的元素。我的问题是var outputArea = document.getElementById("output");有时未定义。

例如,当我单击删除按钮时,它可能没有任何响应,但我第二次单击该按钮时,它会起作用。

window.onload = function () {
    document.getElementById("add").onclick = addParagraph;
    document.getElementById("delete").onclick = deleteLastParagraph;    
}

function deleteLastParagraph() {
    var outputArea = document.getElementById("output");
    var numberOfParas = document.getElementById("output").childElementCount;
    if (outputArea.childNodes[0] == null) {
        alert("No paragraph delete!");
    }
    // outputArea.removeChild(outputArea.childNodes[0]);
    outputArea.removeChild(outputArea.childNodes[numberOfParas - 1]);
}


function addParagraph() {
    var textToAdd = document.getElementById("input").value;
    var outputArea = document.getElementById("output");
    var paragraph = document.createElement("p");
    paragraph.innerHTML = textToAdd;
    outputArea.appendChild(paragraph);
}
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <script src="task4.js" type="text/javascript"></script>
    <style>
        #output {
            border: blue 5px solid;
            padding: 10px;
            margin-bottom: 10px;
            margin-top: 10px;
            width: 50%;
        }

        #output p {
            padding: 10px;
            border: black 1px dashed;
        }
    </style>
</head>
<body>
<h2> Creating, Appending and Deleting Nodes in the DOM Tree </h2>
<p> Type in text below, click add to add as paragraph.
    <button id="add"> ADD</button>
</p>
<textarea id="input" rows="10" cols="60">
</textarea><br>
<button id="delete">Delete Last Paragraph</button>
<br><br>
<h2> Added Paragraphs </h2>
<div id="output">
</div>
</body>
</html>

标签: javascriptdom

解决方案


只是像使用基本文本输入一样运行代码时,我没有看到任何重大问题。这让我相信您的问题可能是由于使用 innerHTML 来设置您的 p 标签的内容。innerHTML 允许您输入中的任何 html 呈现为 html 而不是文本,这可能会以奇怪的方式破坏文档。尝试使用Node.textContent来设置文本。

您还需要在警报语句之后返回以避免引发错误。


推荐阅读