如何在文本框中保留文本

3

我有一个链接,它的目的是在单击时动态添加文本框。但问题是,如果我在先前生成的文本框中输入文本并单击链接,文本框会生成,但页面会刷新并且已输入的文本被重置。

HTML文件

<script>
    var countBox =3;
    var boxName = 0;
    function addInput()
    {
        var boxName="textBox"+countBox; 
    document.getElementById('responce').innerHTML+='<br /><input type="radio" name="choices"  value="o'+countBox+'" id="o'+countBox+'"/><label>Option '+countBox+':</label> <input type="text" id="option'+countBox+'" name="option'+countBox+'"" placeholder="Enter here..."  /><br/>';
        countBox += 1;
    }
</script>
<br /><a href="javascript:void()" onclick="addInput()">Add another</a>(max.5)

如何添加文本框并保留文本框中的文本。希望您理解我的问题。
提前感谢。

你需要在页面刷新之间保存页面状态吗?使用Cookies。 - mishik
页面刷新时数据将丢失,除非您在代码中使用一些会话或cookie的概念! - user2412575
尝试附加输入类型。 - Muhammad
1个回答

8
页面没有刷新,因此这不是问题。问题在于你正在使用 .innerHTML += 来添加新元素。这将会破坏重建现有元素:元素被序列化为 HTML,然后你在连接字符串以添加新的 HTML,在赋值后浏览器必须解析 HTML 来再次创建 DOM 元素。在这个过程中所有数据都将丢失。
应该使用 DOM 操作方法,例如使用document.createElement创建元素,再用Node.appendChild添加元素。
使用 .innerHTML 覆盖现有内容或初始化元素是可以的。但是在现有元素中添加元素可能会导致问题(如上所述),因此最好在这种情况下避免使用它。
示例:
function addInput() {
    var boxName="textBox"+countBox; 
    var input = document.createElement('input');
    input.id = input.name = 'option'+countBox;

    var parent = document.getElementById('responce');
    parent.appendChild(document.createElement('br'));
    parent.appendChild(input);
    // create/add other elements...
    countBox += 1;
}

或两者混合使用:
function addInput() {
    var boxName="textBox"+countBox; 
    var container = document.createElement('div');
    container.innerHTML = '<input type="radio" name="choices"  value="o'+countBox+'" id="o'+countBox+'"/><label>Option '+countBox+':</label> <input type="text" id="option'+countBox+'" name="option'+countBox+'"" placeholder="Enter here..."  />';

    document.getElementById('responce').appendChild(container);
    countBox += 1;
}

4
+1 我也在发同样的内容,但这个已经说得很清楚了。无论如何,这是我的代码,包括完整的转换过程:http://jsfiddle.net/UkeuH/ - MrCode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接