首页 > 解决方案 > 如何在 Jade 中动态构建 jsTree?

问题描述

我正在使用 jquery、jstree、jade 和 nodejs。我的目标是动态生成一棵树,但它失败了。

内联 javascript 代码工作正常,但没有树输出。当我检查 html 时,很明显,jade 在打开 li 标记之前关闭了第一个 ul 标记。

这是玉代码:

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    link(rel='stylesheet', href='https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css')
    script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js')  
    script(src='https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js')  
    script.
        $(document).ready(function() {
            $('#selTree').jstree(ghcomp);
        });
body
  #selTree
    ul
    -for(let r=1; r<ghcomp.length; r++) {
    -for(let gh in ghcomp[r]) {
      li #{gh}
        ul
        -for(let c=0; c<ghcomp[r][gh].length; c++) {
          li #{ghcomp[r][gh][c].comp}
        -}
    -}
    -}    

这是玉产生的输出:

<div id="selTree"><ul></ul><li>I<ul></ul><li>B</li></li><li>L<ul></ul><li>1</li><li>2</li></li><li>M<ul></ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>e</li></li><li>Production<ul></ul><li>virtual</li></li><li>Tech<ul></ul><li>na</li></li><li>Themato<ul></ul><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li></li></div>

我怎样才能在这里控制生产过程?

例如:我可以轻松地动态生成 HTML。我可以把它交给玉吗?

谢谢你。

标签: javascriptpugjstree

解决方案


你可以在原生 Jade迭代中重写它,它会为你正确构建 DOM,更不用说更容易阅读和调试了。我还建议在像这样的复杂嵌套迭代中使用更具描述性的变量名称。

ul
  each gh, ghIndex in ghcomp
    li= gh
      ul
        each c in gh
          li= c

如果您发布了提供 Jade 模板的 JSON,将更容易准确地理解您想要在此处执行的操作,但以下是我看到的问题:

Jade 在嵌入之前关闭 ul 标签的原因li是您没有缩进下一行,因此它将是 ul 的兄弟而不是孩子:

ul
-for(let r=1; r<ghcomp.length; r++) {

ul
-for(let c=0; c<ghcomp[r][gh].length; c++) {

这些应该更改为(如果您坚持使用此方法):

ul
  -for(let r=1; r<ghcomp.length; r++) {

ul
  -for(let c=0; c<ghcomp[r][gh].length; c++) {

推荐阅读