将"this"添加到jQuery中的"each"的父堆栈中

Mat*_*rym 3 arrays jquery parents stack

这个问题有点像两个问题.首先是标题问题.这是我得到的:

// Report all of the parents
$(this).parents().each(function(i){

    // Collect the parts in a var
    var $crumb = '';

    // Get the tag name of the parent
    $crumb += "<span class='tagName'>"+this.tagName+"</span>";

    // And finally, report it
    $breadcrumbs.prepend($crumb);

});
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不包括实际元素本身,只包括父母.有什么方法可以说"这和父母"吗?

现在,第二个问题.如果我无法添加到堆栈中,我如何将该函数的内容分成另一个函数,同时保留它的"this"能力?会是这样的:

// Function to report the findings
function crumble(e){

    // Collect the parts in a var
    var $crumb = '';

    // Get the tag name of the parent
    $crumb += "<span class='tagName'>"+this.tagName+"</span>";

    // And finally, report it
    $breadcrumbs.prepend($crumb);

};
$(this).parents().each(crumble());
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的时间!

CMS*_*CMS 7

对于第一个问题,您可以使用以下.andSelf方法:

$(this).parents().andSelf().each(function () {
  // ..
});
Run Code Online (Sandbox Code Playgroud)

您必须注意一些事情,该$crumb变量是本地范围的,因此它将在您each循环的每次迭代中初始化.

对于你的第二个问题,是的,你可以定义一个函数来完成each回调的工作,你只需要传递对它的引用,而不是调用它(删除parens):

$(this).parents().each(crumble);
Run Code Online (Sandbox Code Playgroud)