在浏览器中显示HTML标记,无需呈现 [英] Display HTML markup in browser without it being rendered

查看:124
本文介绍了在浏览器中显示HTML标记,无需呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开始执行JavaScript,我需要进行故障排除,并希望将HTML输出到屏幕,而无需渲染。我可以通过

Starting to implement Javascript, I need to do troubleshooting and would like to output HTML to the screen without it being rendered. I can access the element (in IE) by

document.getElementById("test").outerHTML

我想,但我无法证明我得到的确定。

I think, but I can't prove what I'm getting to be sure.

那么我该怎么做才能使 document.write 显示包含标签的整个元素?

So what do I do to have document.write show the entire element including tags?

推荐答案

做两件事(所有这些,不只是一个):

Do two things (all of these, not just one):


  1. 将HTML标记替换为实体: b $ b
  2. 将其包装在< pre>< / pre> 标签中,以便空白不被消除,并以等宽字体显示。 >
  1. Replace HTML markup with entities: HTML.replace(/&/g, '&amp;').replace(/</g, '&lt;') is enough.
  2. Wrap it in <pre></pre> tags so the whitespace is not eliminated and it is shown in a monospace font.

您还可以 alert(HTML)。在Windows上的IE(至少)中,您可以按Ctrl-C并将对话框的文本内容粘贴到其他位置,以便看清楚。

You can also alert(HTML). In IE on Windows (at least) you can press Ctrl-C and paste the text contents of the dialog box elsewhere to see it plainly.

两个串行替换速度比使用函数作为第二个参数 replace()。当字符串非常长时,三个串行替换也会更快,因为可能需要一个完整的HTML文档。

Two serial replaces is faster than using a function as the second argument of replace(). Three serial replaces is also faster when the string is very long as one might expect from a full HTML document.

另外,使用 document.write 可能不是最好的方法。如果你有一个id为$ 输出的div,你可以这样访问:

Also, using document.write is probably not the best way. If you have a div with id output you can access it this way:

document.getElementById('output').innerHTML = '<pre>' + document.body.innerHTML.replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</pre>';

上面的代码工作,我在IE中测试,还有使用FireBug的Firefox。请注意,Firefox中不支持 outerHTML

The above code works, I tested it in IE and also in Firefox using FireBug. Note that outerHTML is not supported in Firefox.

这篇关于在浏览器中显示HTML标记,无需呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆