首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从动态HTML数组创建对象

从动态HTML数组创建对象
EN

Stack Overflow用户
提问于 2015-09-16 22:44:17
回答 1查看 41关注 0票数 0

我希望在javascript中获得一个对象,其中包含动态生成的数组中的值,顺序正确,这样以后我就可以对该对象进行then编码,并将其保存到我的数据库中。(也许有一种不同的更简单的方法)

这是表格

代码语言:javascript
复制
 <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>

下面是我用来创建这个数组的函数:

代码语言:javascript
复制
    $('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,而不是实际的值。

代码语言:javascript
复制
$( "#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/

EN

回答 1

Stack Overflow用户

发布于 2015-09-17 00:06:54

尝试这段代码,我希望我正确理解了你的问题。

代码语言:javascript
复制
$("#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));
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32611861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档