开发者

.each() and $(this)

This 开发者_如何学Pythonis my code:

$myDiv = $('<div>1</div>');

$myDiv.each(function () {
    console.log(this.html());
});

It produces an error because this should be $(this). But wait. Isn't $myDiv a jQuery object in the first place, so that this must also be a jQuery object. If so, why should I wrap this inside of $( )?


A jQuery object is more or less an array of regular DOM elements. each iterates over these. this is just a DOM element whereas $(this) generates a one-element array of DOM elements with access to the jQuery API functions.


In that case this actually refers to the node.

$myDiv = $('<div>1</div>');

$myDiv.each(function () {
    console.log(this.innerHTML);
});
// outputs 1


Basically anything fetched as $() becomes part of an array which jQuery adds it's helper methods to, the .each() method actually iterates over each element in the array. That is, it's just the element and not the jQuery array that has all the nice helper methods.


As I understand it, this is a DOM object. Try this code to see:

$myDiv = $('<div>1</div>'); $myDiv.each(function () { alert(this.nodeName); });


According to the jquery documentation this is the expected behavior for the $(selector).each() They even give you an example for the case where "you want to have the jQuery object instead of the regular DOM element": http://api.jquery.com/each/#example-1


When you create an HTML object in jQuery like you did it returns the DOM element. If you really wanted to set the HTML of your new dom element you'd have to call the innerHTML property like so:

$myDiv.each(function () {
    console.log(this.innerHTML);
});

For reference here's the jQUery API on creating DOM elements: http://api.jquery.com/jQuery/#jQuery2

Also, I'm not sure why you'd call the each function on a single element that has just been created?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜