0

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

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

以下是递归脚本的设置方式,调用位于底部。

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/

4

2 回答 2

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/

于 2012-12-30T21:39:23.677 回答
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, '', '- ');
于 2012-12-30T21:21:13.737 回答