将输入字段添加到div容器(javascript) [英] Add input fields to div container (javascript)

查看:180
本文介绍了将输入字段添加到div容器(javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些html数据添加到div容器的末尾。
目前,我使用innerHtml:

I want to add some html data to the end of a div container. Currently, I do it with using innerHtml:

<script language="javascript">
var addid = 0;

function addInput(id){
    var docstyle = document.getElementById('addlist').style.display;
    if(docstyle == 'none')
        document.getElementById('addlist').style.display = '';

    addid++;

    var text = "<div id='additem_"+addid+"'><input type='text' size='100' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput("+addid+")' id='addlink_"+addid+"'>add more</a></div>";

    document.getElementById('addlist').innerHTML += text;
}
</script>

<div id="addlist" class="alt1" style="padding:10px;">
    New list items are added to the bottom of the list.
    <br /><br />
</div>

问题是,一旦添加了另一个输入字段,输入字段中输入的值就会被删除。
如何添加内容并保留输入的数据?

The problem is that the value that was entered in the input fields is removed once another input field is added. How can I add content without and keep the entered data?

PS:我不使用jQuery。

PS: I do not use jquery.

推荐答案

innerHTML 更改重置表单元素。而是使用 appendChild 。请参阅此演示 http://jsfiddle.net/5sWA2/

innerHTML changes reset form elements. Instead use appendChild. See this demo http://jsfiddle.net/5sWA2/

function addInput(id) {

    var addList = document.getElementById('addlist');
    var docstyle = addList.style.display;
    if (docstyle == 'none') addList.style.display = '';

    addid++;

    var text = document.createElement('div');
    text.id = 'additem_' + addid;
    text.innerHTML = "<input type='text' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput(" + addid + ")' id='addlink_" + addid + "'>add more</a>";

    addList.appendChild(text);
}

这篇关于将输入字段添加到div容器(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆