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.parentNode.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 meant ele.parentNode
, but see below. .target
, I take it e
is an event. But you pass parent
, which probably isn't an event. ele.parentNode
is valid before getting it's properties. 您可能想看看它们如何在jQuery中实现parents
函数。
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.