简体   繁体   English

使用javascript将嵌套列表转换为缩进的纯文本

[英]Converting nested list into indented plain text with javascript

I was wondering if is there any way to convert the following HTML list into indented plain text, i've tried the following solution with jQuery (but unfortunately, it add a tab character to the pre.code html element as well, when it should be only on the console.log output) 我想知道是否有任何方法可以将以下HTML列表转换为缩进的纯文本,我已经尝试使用jQuery以下解决方案(但是不幸的是,它应该在pre.code html元素中添加制表符,何时应该仅在console.log输出上)

  function serializeCode() { $.each($("pre.code"), function() { if ($(this).parent().parent().hasClass("multiline")) { console.log($(this).prepend("\\t").text()); } }); } 
 <style> pre.code {display:none} </style> <ul id="list"> <li> <pre class="visual">Comando 1</pre> <pre class="code">command1</pre> </li> <li> <pre class="visual">Comando 2 {</pre> <pre class="code">command2 {</pre> <ul class="multiline"> <li> <pre class="visual">Comando 3</pre> <pre class="code">command3</pre> </li> </ul> <pre class="visual">}</pre> <pre class="code">}</pre> </li> </ul> 

Plain text output 纯文本输出

Comando 1
Comando 2 {
    Comando 3
}

I solved it! 我解决了!

The function below iterate through all pre.code elements on the list, and add a tab character ( \\t ) on the beginning of elements that have a parent with the multiline class. 下面的函数遍历列表中的所有pre.code元素,并在具有multiline类父级的元素的开头添加一个制表符( \\t )。

function serializeCode() {
    console.clear();
    $.each($("pre.code"), function() {
        if ($(this).parent().parent().hasClass("multiline")) {
            console.log("\t" + $(this).text());
        } else {
            console.log($(this).text());
        }
    });
}
var a = '';
$.each($('.visual'), function () {
a += $(this).text() + '\n';
});
alert(a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM