在DOM上动态创建元素,但不发送任何内容

时间:2015-09-03 15:33:09

标签: javascript html dom

我有一个表单,其中一些字段根据另一个字段动态添加,我能够使它创建元素,但是当我发送表单时,这些都不会与加载的非动态字段一起发送在页面加载。

以下是我添加

的方法
function foo(field) {
var selectionDiv = document.getElementById("div_" + field);

var divLength = selectionDiv.children.length;
for (var i = 0; i < divLength; i++) {
    if (selectionDiv.children[i].id.indexOf(field) != -1) {
        var element = document.createElement(selectionDiv.children[i].tagName);
        element.setAttribute("type", selectionDiv.children[i].type);
        element.setAttribute("value", selectionDiv.children[i].value);
        element.setAttribute("id", selectionDiv.children[i].id);
        if (selectionDiv.children[i].className != "") {
            element.setAttribute("class", selectionDiv.children[i].className);
        }
        $(element).appendTo("#div_" + field);
    }
}
}

插入后的HTML:

<form action="/URL" id="form" method="post" name="form" onsubmit="Confirmation('Are you sure?');return false;"><div class="form-horizontal">
<...OtherFields...>
<div class="form-group" id="form_group_test">
<label class="col-xs-2 control-label" for="Identity">test:</label>
<div class="col-xs-4" id="div_test">
        <input id="Fields_test__Identity" name="Fields[test].Identity" type="hidden" value="test">
        <input class="form-control hasTooltip" data-placement="right" data-toggle="tooltip" id="Fields_test__Value" name="Fields[test].Value" title="" type="text" value="*">
        <br>
        <button type="button" onclick="foo('test'); return false;" class="btn btn-default hasTooltip form-control" data_toggle="tooltip" data_placement="right" title=""><span class="glyphicon glyphicon-plus blue"></span></button>
        <input type="hidden" value="test" id="Fields_test1__Identity"><input type="text" value="*" id="Fields_test1__Value" class="form-control hasTooltip"></div>
<...MoreFields...>
</form>

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

当您动态创建元素时,属性&#34; name&#34;缺少,请尝试以下代码:

function foo(field) {
var selectionDiv = document.getElementById("div_" + field);

var divLength = selectionDiv.children.length;
for (var i = 0; i < divLength; i++) {
    if (selectionDiv.children[i].id.indexOf(field) != -1) {
        var element = document.createElement(selectionDiv.children[i].tagName);
        element.setAttribute("type", selectionDiv.children[i].type);
        element.setAttribute("value", selectionDiv.children[i].value);
        element.setAttribute("id", selectionDiv.children[i].id);
        element.setAttribute("name", selectionDiv.children[i].id);
        if (selectionDiv.children[i].className != "") {
            element.setAttribute("class", selectionDiv.children[i].className);
        }
        $(element).appendTo("#div_" + field);
    }
}
}