微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-如何将表单序列化为对象(具有树结构)?

我有一个表格

<form>
    <input type="text" name="Name" />
    <input type="checkBox" name="Feature.Translate" />
    <input type="checkBox" name="Feature.Share" />

    <input type="submit" value="Convert into an object" />
</form>

我想将其转换为对象

{
    Name: "John Connor's Terminator",
    Feature:
    {
        Translate: true // if checked
        // Share wasn't checked
    }
}

如何将表单映射到具有此树结构的对象?

解决方法:

添加方法可帮助您构建树

// add keys to an object as a tree
// ["a", "b", "c"] will generate
// a { b: { c: def } }
// def is the value of the leaf node
var AddToTree = function(obj, keys, def)
{
    for (var i = 0, length = keys.length; i < length; ++i)
        obj = obj[keys[i]] = i == length - 1 ? def : obj[keys[i]] || {};
};

为jQuery选择器创建一个函数,该函数将转换对象中的表单

$.fn.serializeObject = function()
{
   var o = {}; // final object
   var a = this.serializeArray(); // retrieves an array of all form values as
                                  // objects { name: "", value: "" }

   $.each(a, function() {
       var ns = this.name.split("."); // split name to get namespace
       AddToTree(o, ns, this.value); // creates a tree structure
                                     // with values in the namespace
   });

   return o;
};

使用这两个函数定义,可以在“提交”按钮上设置事件:

$(":submit").click(function(e){
    // contains the object from the form
    // respecting element namespaces
    var obj = $("form").serializeObject();
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐