开发者

A javascript recursion problem

开发者 https://www.devze.com 2022-12-09 02:42 出处:网络
I\'m writing a js recursion function to find all ancestors of an element a user clicked on. my code is like this:

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


  1. parent is undefined. You may have meant ele.parentNode, but see below.
  2. By name convention and by .target, I take it e is an event. But you pass parent, which probably isn't an event.
  3. 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);
  }
}
0

精彩评论

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