在 jQuery 中为每个循环嵌套嵌套的 $(this)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16346206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Targeting $(this) within nested for each loops in jQuery
提问by mmmoustache
I'm trying to figure out, when iterating through some list items, how to target each "$(this)" equivalent within nested foreach loops. Here is an example of my problem:
我试图弄清楚,在迭代某些列表项时,如何在嵌套的 foreach 循环中定位每个“$(this)”等价物。这是我的问题的一个例子:
$('li').each(function(){
// I believe $(this) would target each li item...
$(this).children("li").each(function(){
// ... but how can I target each of these li items? Doesn't $(this) target the original loop?
});
});
回答by Gabe
$('li').each(function(){
var $this = $(this);
$this.children("li").each(function(){
$this; // parent li
this; // child li
});
});
回答by mmmoustache
Don't use this
! Use function parameters!
不要用this
!使用函数参数!
$('li').each(function(i, li){
$(li).children("li").each(function(ii, li2){
$(li)...
$(li2)...
});
});
This is more in keeping with the native JavaScript iterators.
这更符合原生 JavaScript 迭代器。
...though an <li>
can't be the direct child of another <li>
...虽然<li>
不能是另一个的直接孩子<li>
回答by Elias Van Ootegem
Look at the basic "prototypes" of jQuery functions (or methods, if you will):
查看 jQuery 函数(或方法,如果您愿意)的基本“原型”:
$[jQobject].[func]([callback]);
The callback is the function that will be invoked in the context of the jQ object. The context being this
, obviously. Put simply that means that:
回调是将在 jQ 对象的上下文中调用的函数。this
显然,上下文是。简单地说就是:
$('#foo').click(function(){});
/\ /\
|| Is the context ||
=====================
The same applies to your case, regardless of the loops being nested or not:
这同样适用于您的情况,无论循环是否嵌套:
$('ul').each(function()
{
//this is ul
var that = this;//you'll often see code like this
$('li', this).each(function()
{
//this is li
//that is parent ul
});
});
回答by SLaks
but how can I target each of these li items? Doesn't $(this) target the original loop?
但是我怎样才能针对这些 li 项目中的每一个呢?$(this) 不是针对原始循环吗?
Nope.
不。
this
comes from the function you're directlyin.
this
来自您直接进入的函数。
回答by Blender
Nope, this
refers to each of the child <li>
items. Try it out.
不,this
是指每个子<li>
项。试试看。
Most (if not all) DOM-interacting jQuery callbacks set this
to to the DOM element that you're working with.
大多数(如果不是全部)DOM 交互 jQuery 回调设置this
为您正在使用的 DOM 元素。
You could also write:
你也可以这样写:
$('li').children("li").each(function(){
var $this = $(this);
});