gpt4 book ai didi

javascript - 无法从动态创建的表单中获取表单

转载 作者:搜寻专家 更新时间:2023-10-31 08:52:06 25 4
gpt4 key购买 nike

我有一个按钮,可以使表单出现在我的 html 页面中。我有一个从表单获取数据的函数:

function getFormData($form){

var unindexed_array = $form.serializeArray();

var indexed_array = {};

$.map(unindexed_array, function(n, i){

indexed_array[n['name']] = n['value'];

});

return indexed_array;

该函数似乎运行良好,因为我可以从其他非动态创建的表单中获取数据。我通过单击按钮以这种方式创建表单:

var new_form = document.createElement('form');
new_form.id = "new_form";

// (...) all the inputs for the form

// and I append to an existent div
existent_div.appendChild(new_form);
// and then the inputs
new_form.appendChild(input1); (...)

我有另一个按钮应该负责获取表单数据。它调用这个函数,在函数中间我有这个:

var new_form_info = getFormData($("#new_form"));
// I get an empty object...

为什么会这样?我不是经验丰富的程序员,如有任何错误,我深表歉意...

最佳答案

你有理由混合使用纯 js 和 jquery 吗? JQuery 表单创建可以帮助您。

var new_form = $('<form></form>')
.attr('id', "new_form")
.append('<input type="text" value="1" name="inp" />');
$('#existent_div').append(new_form);
console.log($('#new_form').serializeArray());

https://jsfiddle.net/yej5xc8s/

更新

如果您追加输入并定义 existent_div

,则混合也有效
function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});

return indexed_array;
}

var new_form = document.createElement('form');
new_form.id = "new_form";
var input = document.createElement('input');
input.name = "qwer";
input.value = "1";
new_form.appendChild(input);

var existent_div = document.getElementById('existent_div');
existent_div.appendChild(new_form);

console.log(getFormData($("#new_form")));

https://jsfiddle.net/yej5xc8s/1/

关于javascript - 无法从动态创建的表单中获取表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39871119/

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