【问题标题】:Is there anyway to add items to an existing list in the DOM (javascript)是否有将项目添加到 DOM 中的现有列表(javascript)
【发布时间】:2016-06-14 09:17:59
【问题描述】:

提前感谢大家提供的任何帮助。

我的目标是在用户单击“添加”按钮时从文本字段中获取用户输入并将其直接添加到 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); 

【问题讨论】:

  • 请查看How to Ask。你的问题太笼统了。您没有表现出任何解决您自己问题的尝试,并且所写的内容作为“给我代码”请求而消失。
  • 他们确实展示了他们尝试过的代码,但是他们没有正确显示的图像。我解决了这个问题,但@Akeem 你真的应该将代码添加为文本。不是图片。
  • 好的,让我修改一下我的问题。
  • 怎么不工作了?代码在运行吗?如果它正在运行,是否会引发异常(在开发者工具-> 控制台下查看)?如果是这样,错误是什么?
  • 感谢您的回复。我使用 Cloud9 作为我的工作区,我正在尝试定位调试器以查看问题可能是什么。到目前为止,代码将毫无问题地运行,但是当我单击添加按钮提交我的测试条目时,该条目将不会显示在我为我的列表提供的部分中。

标签: javascript dom javascript-events


【解决方案1】:

我已将您的代码放入 https://jsfiddle.net/s5xzazL1/1/ 的 jsfiddle 中。请注意,只有第一个列表和输入具有连接到它的事件。

您可以使用浏览器的开发者工具查看异常情况,例如在 chrome 菜单 => 更多工具 => 开发人员工具中。如果您随后看到控制台,您将看到错误

Uncaught TypeError: Cannot read property 'appendChild' of undefined

当您输入 valuer 并单击添加按钮时,列表将替换为您添加的文本,这是由于您的代码行

document.getElementById('list-one-item').innerHTML = addOne;

这是不正确的,应该删除。

异常是由于变量list 为空。然而它被用作该行中的一个对象

list.appendChild(listOne);

List为null,是因为对点击事件的参数有一些误解。

您的代码:

function addListOne(addOne,listItem,listOne,list){
    ...
}

buttonone.addEventListener( 'click', addListOne, false); 

您的代码期望使用 4 个参数调用 addListOne,当点击事件调用 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); 

看到在https://jsfiddle.net/s5xzazL1/5/运行

【讨论】:

  • 非常感谢您的回复。我很抱歉我的回复这么晚了。让我试试代码,看看我能不能让它工作。我一直在尝试一些不同的方法,几乎​​决定使用数组。但我更喜欢使用更简单的选项。
猜你喜欢
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多