在jQuery中为"each"添加"this"到父级堆栈

3
这是一个有两个部分的问题。首先是标题的问题。以下是我所了解到的内容:
// 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);

});

不幸的是,这并不包括实际的元素本身,只有其父元素。是否有一种方法可以说出类似于“这个和它的父元素”?

现在,第二个问题。如果我无法添加到堆栈中,那么我如何将该函数的主体分离到另一个函数中,同时保留其“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());

非常感谢您抽出时间!

1个回答

7

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

$(this).parents().andSelf().each(function () {
  // ..
});

需要注意的是,$crumb变量是局部作用域的,因此它将在每次each循环迭代中初始化。

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

$(this).parents().each(crumble);

不错!谢谢。你能推荐一些有关调用/不调用函数(如crumble)的参考资料吗?我想学习更多 =) - Matrym
哦,关于你的解决方案,这里有一个有趣的小事实。它颠倒了堆栈的顺序!使用reverse()或append(而不是prepend)很容易解决。 - Matrym

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接