输入元素未找到其值

时间:2015-01-21 08:53:26

标签: javascript html

function makeUL() {

var products = JSON.parse(localStorage["products"]);

var list = document.createElement('ul');

for(var i = 0; i < products.length; i++) {
    if(products[i].amount == 0) {
        continue;
    }
    // Create the list item:
    var item = document.createElement('li');

    var product = products[i];

    var totalPrice = product.amount * product.price;
    var toDisplay = product.name + " " + product.amount + " @" + totalPrice + " ";

    // Set its contents:
    item.appendChild(document.createTextNode(toDisplay));
    var inputbox = document.createElement("input");
    inputbox.setAttribute("id", "inputboxProduct" + i);
    inputbox.addEventListener("change", function(){
        changeAmountProd(inputbox.id);
    });
    item.appendChild(inputbox);

    // Add it to the list:
    list.appendChild(item);
}

// Finally, return the constructed list:
return list;
}

当您将鼠标悬停在某个字符串上时,这基本上会生成一个列表。该列表将基于localstorage并为该列表的每个点创建一个输入框。 问题是添加eventlisteners。由于某种原因,当触发该输入框的事件时,它总是返回一个空值。

function changeAmountProd(inputboxId) {
var products = JSON.parse(localStorage["products"]);

value = document.getElementById(inputboxId).value;

if(value < 1) {
    return;
}
products[i].amount = value;

localStorage["products"] = JSON.stringify(products);

makeUL();
}

2 个答案:

答案 0 :(得分:2)

试试这个:

function makeUL() {

    var products = JSON.parse(localStorage["products"]);

    var list = document.createElement('ul');

    for(var i = 0; i < products.length; i++) {
        if(products[i].amount == 0) {
            continue;
        }
        // Create the list item:
        var item = document.createElement('li');

        var product = products[i];

        var totalPrice = product.amount * product.price;
        var toDisplay = product.name + " " + product.amount + " @" + totalPrice + " ";

        // Set its contents:
        item.appendChild(document.createTextNode(toDisplay));
        var inputbox = document.createElement("input");
        inputbox.setAttribute("id", "inputboxProduct" + i);
        inputbox.addEventListener("change", function(){
            changeAmountProd(this.id);
        });
        item.appendChild(inputbox);

        // Add it to the list:
        list.appendChild(item);
    }

// Finally, return the constructed list:
    return list;
}

答案 1 :(得分:2)

问题在于您change事件的回调。您使用inputbox变量(可通过closure获取)引用已更改的元素,但在调用回调时,inputbox将始终指向最后一个生成元素。

请改为尝试:

inputbox.addEventListener("change", function(){
    changeAmountProd(this.id);
});

请参阅addEventListener