使用 javascript 将嵌套列表转换为缩进纯文本
Converting nested list into indented plain text with javascript
我想知道是否有任何方法可以将以下 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>
纯文本输出
Comando 1
Comando 2 {
Comando 3
}
我解决了!
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.
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);
我想知道是否有任何方法可以将以下 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>
纯文本输出
Comando 1
Comando 2 {
Comando 3
}
我解决了!
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 themultiline
class.
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);