开发者

Prototype addMethods is returning "undefined"

开发者 https://www.devze.com 2022-12-19 09:47 出处:网络
I\'m attempting to add a method to prototype\'s Element object called locateAncestor(), which will find and return the DOM node based on tagName. My code is as follows:

I'm attempting to add a method to prototype's Element object called locateAncestor(), which will find and return the DOM node based on tagName. My code is as follows:

Element.addMethods({
lo开发者_StackOverflow社区cateAncestor: function(element,tag) {
    element.ancestors().each(function(e) {
        if (tag == e.tagName) {
            alert(e.id);
            return e;
        }
    });
}});

Then I call the code like this:

var form = target.locateAncestor('FORM');
alert(form);

This, of course triggers two alert() boxes. The first, which is called inside the each() loop, and successfully alerts the ID of the element (in this case, a FORM element). Below this first alert(), I return "e" (which when alert() is applied alerts "HTMLFormElement", just as expected. However, when this function is called, the second alert() returns "undefined", not the value I expect to be returned, which of course is "HTMLFormElement".

Is there some crucial step I'm missing here to adding a method, something that I must do to return a value?


You have return statement for each function, but no return statement for locateAncestor function. Also you should use "detect" instead of "each", because you only need one item from the whole array.

Element.addMethods({
locateAncestor: function(element,tag) {
    return element.ancestors().detect(function(e) {
        if (tag == e.tagName) {
            alert(e.id);
            return true;
        }
        return false;
    });
}});
0

精彩评论

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