如何动态地在 Jade 中构建一个 jsTree?

How to build a jsTree in Jade dynamically?

我正在使用 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}
        -}
    -}
    -}    

这里是 jade 输出的结果:

<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。我可以把它交给jade吗?

谢谢。

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

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

如果您发布了提供 Jade 模板的 JSON,那么您会更容易准确地理解您想在这里做什么,但这是我看到的问题:

Jade 在将 li 嵌入其中之前关闭 ul 标签的原因是您没有缩进下一行,因此它将是 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++) {