jQuery - 相当于each(),但针对单个元素

发布于 2024-10-15 02:35:27 字数 158 浏览 1 评论 0原文

each(): 的 jQuery 等效项是什么?

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

当将函数附加到单个元素时(例如 #element ),

What's the jQuery equivalent for each():

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

把回忆走一遍 2024-10-22 02:35:27

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

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

...然后操作它。

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

如果您想要 .each() 的原因是将 DOM 元素引用为 this,那么您实际上并不需要 this 关键字来执行此操作使用它,您可以简单地从 jQuery 对象中获取 DOM 元素。

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

这两者是等效的,并且将检索将在 .each() 中作为 this 引用的 DOM 元素。

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

我注意到,使用 every 来迭代单个元素并不一定是坏事。

好处是您可以轻松访问 DOM 元素,并且可以在新的作用域中执行此操作,这样就不会用变量弄乱周围的命名空间。

还有其他方法可以实现此目的。举个例子:

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

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 );
花开浅夏 2024-10-22 02:35:27

为了直接回答您的问题, .each() 在任何大小的元素集(包括 1)上正常运行。

您也可以完全省略 .each() 调用,只调用 jQuery $('#element') 上的方法。请记住,您可以链接大多数(如果不是全部)jQuery 方法调用,因为它们返回 jQuery 对象。这甚至适用于多个元素,具体取决于方法的作用。

$('#element').doSomething().doSomethingElse();

如果需要多次引用该对象,请创建一个变量:

var $elm = $('#element');
$elm.doSomething();
doSomethingElse($elm);

To directly answer your question, .each() operates normally on element sets of any size including 1.

You can also omit the .each() call completely and just call jQuery methods on $('#element'). Remember that you can chain most if not all jQuery method calls as they return the jQuery object. This even works on multiple elements for the matter, depending on what the methods do.

$('#element').doSomething().doSomethingElse();

If you need to reference the object multiple times, make a variable:

var $elm = $('#element');
$elm.doSomething();
doSomethingElse($elm);
勿忘初心 2024-10-22 02:35:27

使用first()

each() 匹配所有元素,而 first() 仅匹配第一个元素。

还有其他选择器。当你在选择器中使用id时,你只会得到一个元素。这是 .element#element 之间的主要区别。第一个是可以分配给许多元素的类,而第二个是仅属于(最多)一个元素的 id。

如果只返回一个(或 0 个)元素,您仍然可以使用each。此外,如果您想链接一个事件,您可以完全跳过每个事件。当您想要为元素列表中的每个元素执行特定函数时,可以使用each

Use first().

each() matches all elements, while first() matches only the first.

There are other selectors too. When you use the id in the selector, you will only get one element. This is the main difference between .element and #element. The first is a class that can be assigned to many elements, while the second is an id that belongs to only (at most) one element.

You can still use each if only one (or 0) element is returned. Also, you can skip each altogether if you want to link an event. You use each when you want to execute a specific function for each element in the list of elements.

回忆追雨的时光 2024-10-22 02:35:27

如果只有 1 个元素,则可以使用选择器正常访问它。

$('#your_element').your_event(function() {

});

If there is only 1 element, you can access it normally using the selector.

$('#your_element').your_event(function() {

});
岁月静好 2024-10-22 02:35:27

在幕后,each 只是一个 for 循环,它迭代 jQuery 返回的 map 中的每个元素。

它本质上与相同:

var i, map = $('...selector...');
for (i = 0; i < map.length; i++)
{
  someFunction(i, map[i]);
}

†还有更多内容,包括在地图元素的上下文中调用函数等。

它的实现是提供一种在 < 上调用函数的便捷方法。 code>选择中的每个元素。

Behind the scenes, each is just a for loop that iterates through each element in the map returned by jQuery.

It is essentially the same as:

var i, map = $('...selector...');
for (i = 0; i < map.length; i++)
{
  someFunction(i, map[i]);
}

† There's more to it than this, involving calling the function in the context of the map element etc.

It's implementation is to provide a convenient way to call a function on each element in the selection.

掌心的温暖 2024-10-22 02:35:27

你的意思是像 $('#element').children().each()
假设你有一个带有 id 的 ul 之类的东西,并且你想要每个 li 都在里面?

Do you mean like $('#element').children().each()
supposing you have something like a ul with an id and you want the li each inside it?

じ违心 2024-10-22 02:35:27

如果目的是在新范围内调用(非 jQuery)函数,我认为使用“each”仍然是一种有效的(并且可能是最优雅的)方式,并且它仍然符合 jQuery 语法,尽管我同意 Alex,但它感觉不对,因为它可能有一些开销。
如果您可以更改语法,请使用 $('#element')[0] 替换 this (如已接受的答案中所述)。

顺便说一句,有足够声誉的人可以纠正“zzzzBov”关于已接受答案的评论吗?
$('#element')[0]$('#element').get(0) ARE! 相同,如果您希望 jQuery 对象使用 $('#element').first()$('#element').eq(0)

If the intention is to call a (non-jQuery) function in a new scope I think using "each" still is a valid (and probably the most elegant) way and it stays true to the jQuery syntax although I agree to Alex, it feels wrong since it might have some overhead.
If you can change the syntax use $('#element')[0] as replacement for this (as already mentioned in the accepted answer).

Btw could someone with enough reputation please correct the comment of "zzzzBov" about the accepted answer?
$('#element')[0] and $('#element').get(0) ARE! the same, if you want the jQuery object use $('#element').first() or $('#element').eq(0)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文