这个问题有点像两个问题.首先是标题问题.这是我得到的: // 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 c
// 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);
