JavaScript递归函数有助于删除连字符

时间:2012-12-30 21:04:17

标签: javascript recursion

我一直在研究一个递归脚本,它根据标记动态创建一个下拉导航。

这是我到目前为止所做的,但我试图在下拉列表中的每个项目之前删除连字符,除非它在嵌套的子链接中。有没有人有任何想法?

以下是如何设置递归脚本,调用位于底部。

var loadLinks = function runLinks(currDom, currPrependedChar) {

        var dom = currDom;
        var children = dom.children;

        for (var i = 0; i < dom.children.length; ++i) {

            var currentLink = children[i];

            switch (currentLink.nodeName) {
                case 'A':
                    var option = document.createElement('option');
                    option.innerHTML = currPrependedChar + currentLink.text;
                    option.value = currentLink.href;
                    select.appendChild(option);
                    break;
                default:
                    if (currentLink.nodeName === 'UL') {
                        currPrependedChar += currPrependedChar;
                    }
                    loadLinks(currentLink, currPrependedChar);
                    break;
            }
        }
    }

    loadLinks(nav, '- ');

以下是它如何在JSFiddle上运行,您可以看到带有连字符的选择导航 - http://jsfiddle.net/4jeaZ/

2 个答案:

答案 0 :(得分:1)

只需跟踪当前级别:

var loadLinks = function runLinks(currDom,currPrependedChar, currLevel) {
...
option.innerHTML = (currLevel++ < 1 ? '' : currPrependedChar) + currentLink.text;
...
currLevel < 2 || (currPrependedChar += currPrependedChar);
...
loadLinks(currentLink, currPrependedChar, currLevel);
...
loadLinks(nav, '- ', 0);

http://jsfiddle.net/userdude/4jeaZ/5/

答案 1 :(得分:0)

您可以在runLinks函数中添加一个额外的参数,以便它知道当前的前置字符和子链接前置字符。

  var loadLinks = function runLinks(currDom, currPrependedChar, subPrependedChar) {

        var dom = currDom;
        var children = dom.children;

        for (var i = 0; i < dom.children.length; ++i) {

            var currentLink = children[i];

            switch (currentLink.nodeName) {
                case 'A':
                    var option = document.createElement('option');
                    option.innerHTML = currPrependedChar + currentLink.text;
                    option.value = currentLink.href;
                    select.appendChild(option);
                    break;
                default:
                    if (currentLink.nodeName === 'UL') {
                        currPrependedChar += subPrependedChar;
                    }
                    loadLinks(currentLink, currPrependedChar, subPrependedChar);
                    break;
            }
        }
    }

    loadLinks(nav, '', '- ');