【发布时间】:2015-05-05 13:02:41
【问题描述】:
我正在编写一个代码以从div 获取 html 代码并将其放入文本框中进行编辑。
如果我只是获取代码并直接打印它,我会得到:
<h1>hi</h1><p>Sloppy long one line</p><p>and so on</p>
这很难读,所以我想要这样:
<h1>
hi
</h1>
<p>
Sloppy long one line
</p>
<p>
and so on
</p>
我有这个:
function add_code()
{
var html= document.getElementById("body_visual_editor").innerHTML //Gets the code
html= html.replace(/draggable="true"/g, ''); //Removes the draggable attributes that are added to the elements when returning the code to the div
html= html.replace(/id="autoid[0-9]+"/g, ''); ////Removes the auto generated ID's that are added to the elements when returning the code to the div
html= html.replace(/</g, '\n<'); //Adds a line break before tags
html= html.replace(/\n\n/g, '\n'); //Fixes glitch caused by previous line
html= html.replace(/>(?!\n)/g, '>\n'); //Adds line break after tag
document.getElementById("body_code_box").value= html.trim(); //Adds the code to the textarea for editing.
}
它的问题:
当我删除可拖动属性时,它会在标签末尾留下 2 个空格。
当我在标签之前添加换行符时,即使已经有一个换行符,它也会添加额外的换行符,所以我需要html= html.replace(/\n\n/g, '\n') 来删除它。
该修复在代码开头留下了一个额外的换行符,所以我需要修剪来删除它。
它有效,但看起来很草率。有没有更好的方法来写这个更精简和有效?请不要使用 JQuery。
【问题讨论】:
-
我不同意第一个例子很难阅读。
-
@canon: 大概“Sloppy long one line”比示例中的长很多很多..
-
@mellamokb 我认为以这种方式添加换行符(没有制表符或空格用于嵌套)甚至更糟。还不如进行完整的格式化实现,即:prettify.
-
@connon:缩进代码并正确格式化会很好。但由于这一切都是单独使用 JavaScript 完成的,所以我做的格式越多,代码就越复杂,所以现在换行符至少使它具有足够的可读性,可以理解和编辑。
标签: javascript html