开发者问题收集

收到错误“无法读取未定义的属性 appendchild

2021-06-17
1132
<div class="commentArea"></div>
<input class="write" type="text">
<button onclick="summitComment()" class="summit">summit</button>
<script type="text/javascript" src="main.js"></script>
function summitComment() {
    let comments = document.getElementsByClassName('commentArea')[0];

    let makeDiv = document.createElement('div');
    makeDiv.className = 'talking';

    comments.appendChild(makeDiv)

    let makeUser = document.createElement('span');
    let makeMsg = document.createElement('span');
    let makeBtn = document.createElement('button');

    makeUser.className = "commentUserId";
    makeMsg.className = "mentionUserComment";
    makeBtn.className = "deleteReply"; 

    makeMsg.innerHTML = reply.value;
    makeUser.innerHTML = "User_ID";
    makeBtn.innerHTML = "Delete";

    for (i=0; 1; i++) {
        document.getElementsByClassName('talking')[i].appendChild(makeUser)
        document.getElementsByClassName('talking')[i].appendChild(makeMsg)
        document.getElementsByClassName('talking')[i].appendChild(makeBtn)
    }
}

我正在学习 javascript,并尝试为网页创建评论部分。 第一个代码是 HTML 代码,第二个代码是 JS 代码。 但是当我写一些内容并单击提交按钮时,它可以工作。但控制台向我显示错误

Uncaught TypeError: Cannot read property 'appendChild' of undefined

我认为 'createElement' 创建的标签似乎没有被 getElementsByClassName 选择。

我不知道如何解决它。

3个回答

reply 变量未定义,并且末尾的这个循环我认为没有必要

function summitComment() {
    let comments = document.getElementsByClassName('commentArea')[0];
    let reply = document.querySelector('.write');

    let makeDiv = document.createElement('div');
    makeDiv.className = 'talking';

    comments.appendChild(makeDiv);

    let makeUser = document.createElement('span');
    let makeMsg = document.createElement('span');
    let makeBtn = document.createElement('button');

    makeUser.className = "commentUserId";
    makeMsg.className = "mentionUserComment";
    makeBtn.className = "deleteReply";

    makeMsg.innerHTML = reply.value;
    makeUser.innerHTML = "User_ID";
    makeBtn.innerHTML = "Delete";

    
    makeDiv.appendChild(makeUser)
    makeDiv.appendChild(makeMsg)
    makeDiv.appendChild(makeBtn)
}
<div class="commentArea"></div>
<input class="write" type="text">
<button onclick="summitComment()" class="summit">summit</button>
<script type="text/javascript" src="main.js"></script>
54ka
2021-06-17

因为 appendChild 无法从 undefined 读取 您需要在附加之前检查元素是否存在,而不是:

var element = document.getElementsByClassName('talking');
for (i=0; 1; i++) {
    element?.[i]?.appendChild(makeUser)
    element?.[i]?.appendChild(makeMsg)
    element?.[i]?.appendChild(makeBtn)
}
V.Nhat
2021-06-17

尝试使用 if (!!comment) comments.appendChild(makeDiv) 而不是仅使用 comments.appendChild(makeDiv)

Nickce
2021-06-17