gpt4 book ai didi

javascript - 在 DOM 上动态创建元素但不发送任何形式

转载 作者:行者123 更新时间:2023-11-30 12:16:06 25 4
gpt4 key购买 nike

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

这是我添加的方式

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>

有什么想法吗?

最佳答案

当您动态创建元素时,缺少属性“name”,请尝试以下代码:

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);
}
}
}

关于javascript - 在 DOM 上动态创建元素但不发送任何形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32379887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com