开发者

Adding "this" to the parents stack for "each" in jQuery

This question is a bit of a two-parter. First, the title question. Here's what I've got:

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

});

Unfortunately, this doesn't include the actual element itself, only the parents. Is there any way of saying something like "this and parents"?

Now, the second question. If I were unable to add to the stack, how would I separate the guts of that function into another function, while retaining the "this" ability of it? Would it be something like:

// 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.开发者_如何学JAVAtagName+"</span>";

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

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

Thanks in advance for your time!


For the first question, you can use the .andSelf method:

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

You have to note something, the $crumb variable is locally-scoped, so it will initialize in every iteration of you each loop.

For your second question, yes, you can define a function that does the job of the each callback, you just have to pass a reference to it, and not invoke it (remove the parens):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜