提前感谢所有人提供的任何帮助。
我的目标是从文本字段中获取用户输入,并在用户点击"添加"时将其直接添加到html中的列表中。按钮。当我在工作区中预览代码时,它允许我在文本字段中输入文本,但它不会显示在我为网页上的列表指定的部分中。代码开头的变量用于我稍后将添加的其他进程。
我的代码是:
var buttonone=document.getElementById('add-item-1');
var buttontwo=document.getElementById('add-item-2');
var compareB=document.getElementById('compare');
var resetB=document.getElementById('reset');
//function to add items to first list
function addListOne(addOne,listItem,listOne,list){
addOne = document.getElementById('item-field-1').value;
document.getElementById('list-one-item').innerHTML = addOne;
listOne= document.createElement('li');
listOne.appendChild(document.createTextNode(addOne));
list.appendChild(listOne);
}
buttonone.addEventListener( 'click', addListOne, false);
答案 0 :(得分:0)
我已将您的代码放入https://jsfiddle.net/s5xzazL1/1/的jsfiddle中。请注意只有第一个列表,并且输入已将事件连接到它。
您可以使用浏览器开发人员工具查看例外情况,例如:在chrome菜单中=>更多工具=>开发者工具。如果您再看到控制台,则会看到错误
Uncaught TypeError: Cannot read property 'appendChild' of undefined
当您输入评估者并单击添加按钮时,该列表将替换为您添加的文本,这取决于您的代码行
document.getElementById('list-one-item').innerHTML = addOne;
哪个不正确,应该删除。
异常是因为变量list
为空。然而它被用作行中的对象
list.appendChild(listOne);
由于对click事件的参数存在一些误解,因此List为null。
您的代码:
function addListOne(addOne,listItem,listOne,list){
...
}
buttonone.addEventListener( 'click', addListOne, false);
您的代码期望使用4个参数调用addListOne,当click事件调用addListOne时,只传递1个参数并且它是事件。
因此,您需要使用document.getElementById
提供代码
var buttonone=document.getElementById('add-item-1');
var buttontwo=document.getElementById('add-item-2');
var compareB=document.getElementById('compare');
var resetB=document.getElementById('reset');
//function to add items to first list
function addListOne(event){
var newText = document.getElementById('item-field-1').value;
var newListItem= document.createElement('li');
newListItem.appendChild(document.createTextNode(newText));
var listOne = document.getElementById('list-one-item');
listOne.appendChild(newListItem);
}
buttonone.addEventListener( 'click', addListOne, false);
运行