微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

// 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());

在此先感谢您的时间!

解决方法

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

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

你必须注意一下,$crumb变量是本地范围的,因此它将在每个循环的每次迭代中初始化.

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐