为什么我的代码只在我的购物清单中添加“null”?

时间:2018-05-19 21:05:38

标签: javascript

我认为意图很明确:您可以按一个按钮或另一个按钮将您输入的项目添加到输入字段中的一个或另一个购物清单。

然而,无论是什么或者我是否写了什么,如果按下其中一个按钮,它只会在列表中添加“null”。

为什么?

function sortItem1() {
    document.getElementById("addToMarket").addEventListener("click", addToMarketList);
}

function sortItem2() {
    document.getElementById("addToOnline").addEventListener("click", addToOnlineList);
}

var gottaBuy = document.getElementById("item");
var listForMarket = " ";
var listForOnlineShop = " ";

function addToMarketList() {
    listForMarket = listForMarket + "<li>" + gottaBuy + "</li>";
    document.getElementById("marketList").innerHTML = listForMarket;
    document.getElementById("item").value = " ";
}

function addToOnlineList() {
    listForOnlineShop = listForOnlineShop + "<li>" + gottaBuy + "</li>"
    document.getElementById("onlineList").innerHTML = listForOnlineShop;
    document.getElementById("item").value = " ";
}

window.addEventListener("load", sortItem1);
window.addEventListener("load", sortItem2);
<h1>What would you like to add?</h1> 
 <input type="text" id="item" /> 
 <button type="button" id="addToMarket">Markt</button> 
 <button type="button" id="addToOnline">Online</button> 
 <h2>Buy at a store:</h2> 
 <ul id="marketList"></ul> 
 <h2>Buy online:</h2> 
 <ul id="onlineList"></ul>

2 个答案:

答案 0 :(得分:1)

var gottaBuy = document.getElementById("item")只是将输入的html标记分配给变量。

您要检索的是输入的值,并根据单击的按钮进行分配。您可以通过在每个按钮处理程序中分配一个单独的变量并附加.value来获取输入值,如下所示:

function addToMarketList() {
    var gottaBuy = document.getElementById("item").value;
    listForMarket = listForMarket + "<li>" + gottaBuy + "</li>";
    document.getElementById("marketList").innerHTML = listForMarket;
    document.getElementById("item").value = " ";
}

function addToOnlineList() {
    var gottaBuy = document.getElementById("item").value;
    listForOnlineShop = listForOnlineShop + "<li>" + gottaBuy + "</li>"
    document.getElementById("onlineList").innerHTML = listForOnlineShop;
    document.getElementById("item").value = " ";
}

jsFiddle: https://jsfiddle.net/AndrewL64/e9t0rszh/1/

答案 1 :(得分:1)

您可以从点击处理程序中选择元素,因此您确定它已经加载。

而且您也很可能想要添加实际值而不是元素本身。

function addToMarketList() {
    var gottaBuy = document.getElementById("item");
    listForMarket = listForMarket + "<li>" + gottaBuy.value + "</li>";
    document.getElementById("marketList").innerHTML = listForMarket;
    document.getElementById("item").value = " ";
}

function addToOnlineList() {
   var gottaBuy = document.getElementById("item"); 
   listForOnlineShop = listForOnlineShop + "<li>" + gottaBuy.value + "</li>"
    document.getElementById("onlineList").innerHTML = listForOnlineShop;
    document.getElementById("item").value = " ";
}