我希望在javascript中获得一个对象,其中包含动态生成的数组中的值,顺序正确,这样以后我就可以对该对象进行then编码,并将其保存到我的数据库中。(也许有一种不同的更简单的方法)
这是表格
<form name="second_form" id="second_form" action="#" method="POST">
<a href="#" id="AddChampion" onclick="return false;">Add Champion</a>
<div id="ChampionInput">
</div>
<input type="submit" name="submit">
</form>下面是我用来创建这个数组的函数:
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion">\
<input type="text" class="ChampionInput">\
<a href="#" class="AddGeneralChange">Add General Change</a>\
<div class="GeneralChanges">\
</div>\
<div>');
});
$('div#ChampionInput').on('click','a.AddGeneralChange', function(){
$(this).siblings('.GeneralChanges').append(
'<div class="GeneralChange">\
<textarea type="text" size="20" rows="3" cols="50" class="GeneralChangeDescription"></textarea>\
</div>');
});下面是我尝试过但没有结果的东西。我试图遍历数组的值,然后把它放到一个对象中,我得到了整个div,而不是实际的值。
$( "#second_form" ).submit( function(event) {
$( "#ChampionInput.ChampionInput :input" ).each( function( index, value ) {
var _value = value;
var _index = index;
alert(value);
$(this).children( ".GeneralChangeDescription").each( function( index, value ) {
});
});
});下面是添加了一些字段http://imgur.com/QXhWSHA后的样子
这里是工作的jSfiddle:http://jsfiddle.net/ss84agxv/
发布于 2015-09-17 00:06:54
尝试这段代码,我希望我正确理解了你的问题。
$("#second_form").submit(function(event) {
//don't do the default action on submit
event.preventDefault();
//Your object as array for the champions
var object = [];
//Loop through each .Champion-div
$('.Champion').each(function() {
//Create a new object for this champion with the value from the input field and an array for the descriptions
var champion = {
'name': $(this).find(".ChampionInput").val(),
'description': []
};
//Loop through each description textfields of this champion
$(this).find('.GeneralChangeDescription').each(function() {
//add the description to the description array of the champion
champion.description.push($(this).val());
});
//finally put the champion in your champion array
object.push(champion);
});
//Thats just for you, an alert of the json-object
alert(JSON.stringify(object));
});https://stackoverflow.com/questions/32611861
复制相似问题