問題描述

我試圖弄清楚,在迭代一些列表專案時,如何在巢狀的 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 函式的基本”prototypes”(或者方法,如果你願意的話):

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

第四種辦法

but how can I target each of these li items? Doesn’t $(this) target the original loop?

不。

this 來自您直接使用的功能。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。