【问题标题】:Targeting $(this) within nested for each loops in jQuery在 jQuery 中为每个循环的嵌套中定位 $(this)
【发布时间】:2013-05-02 19:29:18
【问题描述】:

我试图弄清楚,在遍历某些列表项时,如何在嵌套的 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儿童?
  • 您想遍历<li>s 中的<li>s 吗?

标签: javascript jquery html


【解决方案1】:
$('li').each(function(){
    var $this = $(this);
    $this.children("li").each(function(){
        $this; // parent li
        this; // child li
    });
});

【讨论】:

  • @mmmoustache - 很高兴我能帮上忙
【解决方案2】:

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

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

这更符合原生 JavaScript 迭代器。

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

【讨论】:

  • 那你为什么用this呢? $(this).cildren('li') 而不是 li.children('li')
  • @EliasVanOotegem:'这是复制/粘贴遗漏。感谢您的提醒。
  • 谢谢你,眯着眼睛。直到你的例子,我才得到函数参数!
  • 这个答案应该是 JQuery/SO 知识的一部分!我什至不知道参数。
【解决方案3】:

查看 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
    });
});

【讨论】:

  • 感谢您的解释 - 文档有时有点令人生畏,但您帮助了我!
  • 这个答案也很有教育意义。
【解决方案4】:

但是我怎样才能定位每个 li 项目? $(this) 不是针对原始循环吗?

没有。

this 来自您直接所在的函数。

【讨论】:

    【解决方案5】:

    不,this 指的是每个子 <li> 项目。试试看。

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

    你也可以写:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多