I'm writing a js recursion function to find all ancestors of an element a user clicked on. my code is like this:
/**a global variable.*/
var anc;
function getAncestors(e){
var ele = e.target;
var parentName = ele.p开发者_Go百科arentNode.name;
anc +=bracket(parentName);
if (parentName.toLowerCase() == "undefined" ) return;
else getAncestors(parent);
}
I ran it using firefox, but there's an error message in the error console, "Error: ele.parentNode is undefined".
also, when i reset anc = ' '; it didn't work either.
Thanks!
Paul
parent
is undefined. You may have meantele.parentNode
, but see below.- By name convention and by
.target
, I take ite
is an event. But you passparent
, which probably isn't an event. - You probably want to check that
ele.parentNode
is valid before getting it's properties.
You might want to take a look at how they implement the parents
function in jQuery.
An undefined
value, per Javascript standards, doesn't have a name
attribute -- so rather than trying to get the name
in one gulp, just do a var parent = e.target.parentNode;
and bail out if THAT is undefined!
You should break the recursion like this
if(ele.parentNode) return;
parentNode.name
is not supported by firefox
Maybe try something like this:
var anc = [];
function getAncestors(element) {
if (element.parentNode) {
anc.push(element.parentNode);
getAncestors(element.parentNode);
}
}
精彩评论