在jQuery中针对每个循环嵌套内置$(this)

mmm*_*che 42 html javascript jquery

我试图弄清楚,当迭代一些列表项时,如何在嵌套的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?
    });
});
Run Code Online (Sandbox Code Playgroud)

Gab*_*abe 74

$('li').each(function(){
    var $this = $(this);
    $this.children("li").each(function(){
        $this; // parent li
        this; // child li
    });
});
Run Code Online (Sandbox Code Playgroud)


小智 30

不要用this!使用功能参数!

$('li').each(function(i, li){
    $(li).children("li").each(function(ii, li2){
        $(li)...
        $(li2)...
    });
});
Run Code Online (Sandbox Code Playgroud)

这更符合本机JavaScript迭代器.

......虽然<li>不能成为另一个人的直接孩子<li>

  • 我认为这比公认的解决方案更清晰. (2认同)

Eli*_*gem 10

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

$[jQobject].[func]([callback]);
Run Code Online (Sandbox Code Playgroud)

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

$('#foo').click(function(){});
   /\                 /\
   || Is the context  ||
   =====================
Run Code Online (Sandbox Code Playgroud)

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

$('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
    });
});
Run Code Online (Sandbox Code Playgroud)