开发者

jQuery objects and form.serialize

Here is m开发者_运维技巧y example:

var form= $(".anyclass form");
var sf = form.serialize();
$.post(form[0].action,

Let's suppose that there is only one form in the page that fits the criteria.

Why I need to access the action property using [0]? Why the .serialize() is done without [0]?

Sorry about this newbie question.


I think you want to do it like:

$.post(form.attr('action'));

By the way: you are getting all forms within an element with the class .anyclass. This will return multiple forms (if present). Ýou'll be better of if you gave the form some id and get it that way: $('#myForm').


Your form variable returned from $(...) is a jQuery object that potentially includes references to many form elements.

To access the underlying native DOM elements within that object you either need to use array notation (as above) or form.get(0).

As for the differences in usage, .serialize() is a method of the jQuery object, so has to be called on form.

However .action is a DOM attribute, so you need to use the native DOM element to access it, although you could alternatively have used:

form.attr('action')


the [0] just gives you the straight DOM Object for the Form,

form === jquery object
form[0] === DOM object


That's because .serialize() is a jQuery method that applies for all matched elements.

I haven't looked at the source, but I bet there's something like this:

return this.each(function(i, val){
    // do stuff
})

And when you do form[0].action, you're actually returning the first element (the native DOM element) in the set of matched elements, and then accessing it's native property

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜