但是对于单个元素

但是对于单个元素

本文介绍了jQuery - 相当于each(),但是对于单个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个()的jQuery等价物是什么:

What's the jQuery equivalent for each():

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

,例如 #element

推荐答案

您始终可以在变量中引用jQuery对象:

You can always reference the jQuery object in a variable:

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

...然后操纵它。

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

如果你想要的原因 .each()是将DOM元素引用为这个,你真的不需要这个关键字来做到这一点,你可以简单地从jQuery对象中获取DOM元素。

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

这两个是等价的,并将检索将要的DOM元素在 .each()中引用为

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.

好处是你可以轻松访问DOM元素,并且你可以在一个新的范围内这样做,这样你就不会用变量来混淆周围的命名空间。

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 );

这篇关于jQuery - 相当于each(),但是对于单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:04