javascript - 将缩进文本列表转换为 HTML 列表 (jQuery)

标签 javascript jquery html html-lists

我正在尝试创建一个 jQuery 脚本,它将任意长度和深度的缩进文本列表转换为格式正确的 HTML 列表。我将在其上运行此脚本的列表是简单的目录树结构。在树结构中,文件夹由文件夹名称后面的分号表示(文件没有结束标点符号)。鉴于此,我想附上<span class="folder"></span><span class="file"></span>到适当的行。

我发现生成大部分结构相当容易,但我似乎无法获得递归(我怀疑这是必要的)以确保标签正确嵌套。将实现此功能的页面将包含最新版本(即 3.0.3)的 Bootstrap,因此请随意使用其任何功能。我有大约两打(通常是流产的)代码片段,我已经尝试过这些代码片段,或者我目前正在尝试调整它们以产生所需的结果。我没有发布大量(可能无用的)代码,而是创建了一个 JSFiddle包含用于输入/输出的基本表单、一些 jQuery、示例列表和加载的一些外部库。

任何帮助或建议将不胜感激。

最佳答案

试试这个。我把它复制到你的 fiddle 中,它似乎有效。

var indentedToHtmlList = function indentedToHtmlList (text, indentChar, folderChar, listType, showIcons) {
  indentChar = indentChar || '\t';
  folderChar = folderChar || ':';
  listType = listType || 'ul';
  showIcons = !!showIcons;

  var lastDepth,
      lines = text.split(/\r?\n/),
      output = '<' + listType + '>\n',
      depthCounter = new RegExp('^(' + indentChar + '*)(.*)');

  for (var i = 0; i < lines.length; i++) {
    var splitted = lines[i].match(depthCounter),
        indentStr = splitted[1],
        fileName = splitted[2],
        currentDepth = (indentStr === undefined) ? 0 : (indentStr.length / indentChar.length),
        isFolder = (fileName.charAt(fileName.length - 1) === folderChar);

    if (isFolder) {
      fileName = fileName.substring(0, fileName.length -1);
    }

    if (lastDepth === currentDepth) {
      output += '</li>\n';
    } else if (lastDepth > currentDepth) {
      while (lastDepth > currentDepth) {
        output += '</li>\n</' + listType + '>\n</li>\n';
        lastDepth--;
      }
    } else if (lastDepth < currentDepth) {
      output += '\n<' + listType + '>\n';
    }

    output += '<li>';
    if (showIcons) {
      output += '<span class=" glyphicon glyphicon-' +
      (isFolder ? 'folder-open' : 'file') +
      '"></span> ';
    }
    output += fileName;

    lastDepth = currentDepth;
  }

  while (lastDepth >= 0) {
    output += '\n</li>\n</' + listType + '>';
    lastDepth--;
  }

  return output;
};

关于javascript - 将缩进文本列表转换为 HTML 列表 (jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20578697/

相关文章:

jquery - 如何使用 jquery 根据另一个下拉列表的选择更改下拉列表值

javascript - 使用时间作为动态变量来比较值

javascript - 重新排序不是兄弟的 Div

html - "@media only screen and ()"css 未覆盖

javascript - 如何减小 jQuery UI 的大小?

jQuery 没有向 node.js 服务器发送自定义 header CORS 请求,或者服务器没有收到?

javascript - 将 .addClass 移动到未选择的元素时,jQuery Slider 行为异常

javascript - Node.js:通过服务器响应发送流数据(无管道)

javascript - 在 JQuery 中按日期对表进行排序的问题

javascript - ng-模型在 ng-transclude 中