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

后端 未结 5 1640
执念已碎
执念已碎 2020-12-02 12:29

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:

5条回答
  •  既然无缘
    2020-12-02 13:04

    Look at the basic "prototypes" of jQuery functions (or methods, if you will):

    $[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:

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

提交回复
热议问题