Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

javascript - jQuery - equivalent to each(), but for a single element

What's the jQuery equivalent for each():

$(".element").each(function(){  
  // do stuff
});

when attaching a function to a single element, like #element ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can always reference the jQuery object in a variable:

var $el = $('#element');

...then manipulate it.

$el.doSomething();          // call some jQuery methods from the cached object
$el.doSomethingElse();

If the reason you wanted .each() was to reference the DOM element as this, you don't really need the this keyword to do it, you can simply grab the DOM element out of the jQuery object.

var element = $('#element')[0];       // both of these give you the DOM element
var element = $('#element').get(0);   //        at index 0

The two of these are equivalent, and will retrieve the DOM element that would be referenced as this in the .each().

alert( element.tagName );  // alert the tagName property of the DOM element
alert( element.id );       // alert the ID property of the DOM element

I'd note that it isn't necessarily bad to use each to iterate over a single element.

The benefits are that you have easy access to the DOM element, and you can do so in a new scope so you don't clutter the surrounding namespace with variables.

There are other ways to accomplish this as well. Take this example:

(function( $ ) {

    // Inside here, "this" will refer to the DOM element,
    //    and the "$" parameter, will reference the jQuery library.

    alert( this.tagName );

    // Any variables you create inside will not pollute the surrounding 
    //     namespace.

    var someVariable = 'somevalue'; // is local to this function

}).call( $('#element')[0], jQuery );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...