代码改变世界

JavaScript递归注意事项

2019-05-20 11:38  盛世游侠  阅读(534)  评论(0编辑  收藏  举报
var svg_node = document.getElementById("svgnode")

function parents(posnode,selector)
{
    var flag = false;
    var initials = selector.substr(0,1)
    var aim_parent = posnode.parentNode;
    
    switch(initials){
        
        case "#":
            selector = substring(1,selector.length);
            flag = [].slice.call(aim_parent.id).indexOf(selector) > -1;
        break;
        case ".":
            selector = substring(1,selector.length);
            flag = [].slice.call(aim_parent.classList).indexOf(selector) > -1;
        break;
        default:
            flag = aim_parent.tagName.toLowerCase() === selector;
        break;

    }

    if (flag) {
       return aim_parent;
    }
     
      // 递归调用时,必须在递归调用前面加个return,否则接收的变量会是undefined
      return parents(aim_parent, selector);
}


//  如果在递归调用前面没有return,则k_dom的值会为undefined
var k_dom = parents(svg_node,"li");