jQuery中每个循环的目标$(this)

Targeting $(this) within nested for each loops in jQuery

本文关键字:this 目标 循环 jQuery      更新时间:2023-09-26

我试图弄清楚,当通过一些列表项迭代时,如何在嵌套的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?
    });
});
$('li').each(function(){
    var $this = $(this);
    $this.children("li").each(function(){
        $this; // parent li
        this; // child li
    });
});

不要使用this !使用函数参数!

$('li').each(function(i, li){
    $(li).children("li").each(function(ii, li2){
        $(li)...
        $(li2)...
    });
});

这更符合原生JavaScript迭代器。

…虽然<li>不能是另一个<li>的直接子

看看jQuery函数(或者方法,如果你愿意的话)的基本"原型":

$[jQobject].[func]([callback]);

回调是在jQ对象上下文中调用的函数。显然,上下文是this。简单地说,这意味着:

$('#foo').click(function(){});
   /'                 /'
   || Is the context  ||
   =====================

同样适用于您的情况,无论循环是否嵌套:

$('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
    });
});

但是我如何针对每一个li项呢?$(this)不是以原始循环为目标吗?

不。

this来自于你直接的函数。

不,this指的是<li>的每一个子条目。试一试。

大多数(如果不是全部)DOM交互的jQuery回调将this设置为您正在使用的DOM元素。

你也可以这样写:

$('li').children("li").each(function(){
    var $this = $(this);
});