在javascript中添加一个带有文本组件的li元素

Adding an li element with text component on click with javascript

本文关键字:文本 组件 元素 li 一个 javascript 添加      更新时间:2023-09-26

这就是我到目前为止所做的-但我还需要处理和空评论,在提交和发布多个评论后清除字段。我真的不想要答案-只是提示我需要看哪里,如果我完全错了。

function registerClickHandler() {
   var commentButton = document.getElementByID('postComment');
   commentButton.onclick = addComment();
}
function addComment() {
    var list = document.getElementByID('commentList');
    var commentContent = document.getElementByID('comment')
    var newComment = document.createElement('li');
    newComment.appendChild(document.createTextNode(commentContent));
    list.appendChild(newComment);
}

<ul id='commentList'>
</ul>
<form>
   <input type='text' id='comment'/>
   <input type='button' id='postComment' value='Post'/>
</form>

看一下这个代码工作的例子,基本上你有语法错误:

为getElementByID更改getElementByID的所有货币

document.getElementByID('postComment');

document.getElementById('postComment');
并调用定义click处理程序的函数
registerClickHandler();
获取元素 的值
var commentContent = document.getElementById('comment').value;

一些提示:

  • 没有getElementByID函数,只有getElementById,因为javascript是区分大小写的。
  • commentButton.onclick = addComment();是错误的,因为您调用addComment函数而不是将其分配为onclick事件的事件处理程序。你应该去掉括号commentButton.onclick = addComment;
  • 使用document.getElementById('comment').value;获取或设置文本输入的值