将代码添加到div清除输入val

时间:2015-10-25 02:21:52

标签: javascript html dom

我有一个JS函数,它将类PizzaBox的div添加到一个名为PizzaBoxHolder的空div中。为什么每当创建新行时,输入中的用户输入值都会被占位符替换?另外,作为附注,我是否应该使用占位符进行颜色输入?

function newBox
{
    numOfBoxes += 1; //This is a global variable declared elsewhere, other functions use it but only this one modifies it
    var pizzaBoxCode = "<div class = 'PizzaBox'>"
                     + "    <h6>Box number " + numOfBoxes + "</h6>"
                     + "    <p>Color: <input type = 'color' class = 'boxColor' placeholder = '#000000'/></p>"
                     + "    <p>Toppings: <input type = 'text' class = 'toppings' placeholder = 'Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>"
                     + "</div>";
    var PizzaBoxHolder = document.getElementById("PizzaBoxHolder") //Empty div until this function fills it up
    PizzaBoxHolder.innerHTML += pizzaBoxCode;
}

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

您目前正在执行此操作的方式是重置主innerHTML元素的整个PizzaBoxHolder。通过重置HTML,您将丢失当前值。如果您更改代码以创建元素,然后调用.appendChild,它将按预期工作。原因是,您只是将一个节点附加到当前元素。

var pizza = document.createElement("div");
pizza.className += "PizzaBox";
pizza.innerHTML = "<h6>Box number " + numOfBoxes + "</h6><p>Color: <input type='color' class='boxColor' placeholder = '#000000'/></p><p>Toppings: <input type='text' class='toppings' placeholder='Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>";

var PizzaBoxHolder = document.getElementById("PizzaBoxHolder"); 
PizzaBoxHolder.appendChild(pizza);

Working fiddle