从动态HTML数组创建对象

Creating an object from dynamic HTML array

本文关键字:创建对象 数组 HTML 动态      更新时间:2023-09-26

我想获得一个对象在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));
});