停止清除innerHTML插入上的输入 [英] Stop input from clearing on innerHTML insert
问题描述
我正在设计一种允许用户通过单击按钮添加额外输入字段的表单.
I'm working on a form that allows the user to add extra input fields by clicking a button.
基本上看起来像这样:
<div>
<input type="text" placeholder="existing"/>
</div>
<button class="add">add</button>
带有一些JavaScript:
With a little JavaScript:
var add = document.querySelector(".add");
var div = document.querySelector("div");
add.addEventListener('click', function () {
div.innerHTML += '<input type="text" placeholder="new"/>';
});
但是,我注意到单击按钮时-如果任何现有输入字段都具有值,则会将其清除.
However, I noticed that when the button is clicked - if any existing input fields have values, they get cleared.
我已经摆弄了一段时间,似乎无法找到阻止这种情况发生的解决方案,所以我想知道这里是否有人可以提供帮助.
I've been fiddling around with it for a while and can't seem to find a solution to stop this from happening, so I'm wondering if anyone here can help.
这是一个小提琴 http://jsfiddle.net/gxzLZ/
推荐答案
如果尝试console.log(div.innerHTML)
,您将看到打印的HTML为:
If you try to console.log(div.innerHTML)
you will see that the printed HTML is:
<input type="text" placeholder="existing"><input type="text" placeholder="new">...
在<input>
中键入内容时,不会编辑输入值.您需要保留原始内容,并避免每次都覆盖整个div
内容
When you type something inside the <input>
you don't edit the input value. You need to preserve the original content and avoid to override each time the whole div
content
这是我的处理方式: http://jsfiddle.net/gxzLZ/5/
JS
var add = document.querySelector(".add");
var div = document.querySelector("div");
add.addEventListener('click', function () {
var input = document.createElement('input')
input.type = "text";
input.placeholder = "new";
div.appendChild(input);
});
这篇关于停止清除innerHTML插入上的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!