从动态HTML数组创建对象
Creating an object from dynamic HTML array
我想获得一个对象在javascript与值从我的动态生成的数组在正确的顺序,所以以后我将能够jsonencode该对象,并将其保存到我的数据库。(也许有一种更简单的方法)
格式为
<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 ) {
});
});
});
这是添加一些字段后的图片https://i.stack.imgur.com/8k4Sz.jpg
这里是工作jSfiddle: http://jsfiddle.net/ss84agxv/
试试这个代码,我希望我正确理解了你的问题。
$("#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));
});
相关文章:
- 如何在jquery中从$.each循环创建对象数组
- 无法创建对象数组
- 创建对象数组的封装问题
- 下划线 从对象元素创建对象数组
- 读取 json 以使用 jQuery .each() 创建对象数组
- 基于文件名数据创建对象数组
- 按键/值在数组内创建对象数组
- 如何从字符串创建对象数组
- 如何从javascript中具有相同键的对象创建对象数组,对象中包含数组
- 如何从多个数组创建对象数组
- 如何在json中创建对象数组
- 在javascript中创建对象数组
- 根据id对对象进行分组,并创建对象数组
- 如何使用javascript循环创建对象数组
- 我如何在函数参数中创建对象数组,为每个对象调用函数
- 从数组中创建对象数组
- jQuery .each()创建对象数组
- 如何使用html dom为国家列表创建对象数组
- JavaScript / mongoose - 循环访问数组以创建对象数组
- 如果我们使用new array (len).fil({})创建对象数组;然后在任意一个对象中添加一个键,它会被反射到所有