【问题标题】:Add input fields to div container (javascript)将输入字段添加到 div 容器 (javascript)
【发布时间】:2012-03-16 08:07:24
【问题描述】:

我想在 div 容器的末尾添加一些 html 数据。 目前,我使用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>

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

PS:我不使用 jquery。

【问题讨论】:

    标签: javascript dom innerhtml


    【解决方案1】:

    innerHTML 更改重置表单元素。而是使用appendChild。看这个演示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);
    }
    

    【讨论】:

    • 非常感谢。像魅力一样工作!
    【解决方案2】:

    看看这个http://reference.sitepoint.com/javascript/Node/appendChild

    类似

    document.getElementById('addlist').appendChild(text);
    

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多