javascript - 如何解释 jQuery 中的表单?

标签 javascript jquery html

说,我有这个:

var html = '<form><input type="text" value="v" name="nnn"></form>';

现在我想“反序列化”它,我的意思是获取一个对象/数组,键为nnn,值为v。所以,

{
    nnn: 'v',
    otherInputField: 'itsValue'
}

最佳答案

使用serializeArray

var html = '<form><input type="text" value="v" name="nnn"></form>';
$(html).serializeArray();

demo

如果它绝对必须是一个纯对象,你可以将数组处理成一个对象,如

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Convert form data to JavaScript object with jQuery

关于javascript - 如何解释 jQuery 中的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30213764/

相关文章:

调色板生成器的 javascript 源代码

javascript - 生成多个jquery点击函数

javascript - 如果窗口高度 < 更改 css

javascript - 将行高放在选择框中

jquery - 我如何重新创建滚动时淡入淡出的固定背景设计?

html - html 标签上的背景大小

javascript - 当文本框模糊且为空时隐藏文本框

jquery - animate.css 用于着陆页的欢迎效果

PHP/JQUERY 标签在编辑按钮点击时循环输入

Javascript - 在加载页面内容时将图标/图像放在页面上,并在某些 JS 事件中使用它