开发者

Adding function to jquery

I am writing a function called serializePost.

The function will never be called on a set of objects. only ever one object.

hence my question is;

do I need to do this.each or can I simply use this

Will this work:

(function($) {
    $.fn.serializePost = funct开发者_StackOverflowion() {
        var data = {};
        var formData = $(this).serializeArray();
        for (var i = formData.length; i--;) {
            var name = formData[i].name;
            var value = formData[i].value;
            var index = name.indexOf('[]');
            if (index > -1) {
                name = name.substring(0, index);
                if (!(name in data)) {
                    data[name] = [];
                }
                data[name].push(value);
            }
            else
                data[name] = value;
        }

        return data;
    };
})(jQuery);


No need to use .each(), and no need to wrap it either.

var formData = this.serializeArray();

Inside the plugin, this is already a reference to the jQuery object.


You can observe the source of the .val() function which basically pops the first element off the selection chain and works with it:

var elem = this[0]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜