我已经使用下面的 HTML 代码片段来显示文本,但在 Internet Explorer 8 版本中无法这样做。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="jquery-ui-1.8.20.js"></script>
</head>
<body>
<div>
<pre id="test">
</pre>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#test").html("WELCOME\nHello World")
});
</script>
</body>
</html>
此代码片段在 IE 的最新版本中按预期正常工作,但“\n”在 IE8 版本中不起作用。如何解决这个问题?提前致谢。
最佳答案
尝试更正确的 DOM 操作:
document.getElementById("test")
.appendChild(document.createTextNode("WELCOME\nhelloworld"));
它应该可以工作。
此外,您可以使用outerHTML
强制在 IE 中呈现:
var el = document.getElementById("test")
if (el.tagName == "PRE" && "outerHTML" in el) { // check `outerHTML` exists (it's not in Firefox)
var outer = el.outerHTML;
var preservedAttrs = outer.substring(0, outer.indexOf('>') + 1);
el.outerHTML = preservedAttrs + str + "</PRE>";
}
else {
el.innerHTML = str;
}
另一种方法是使用 nodeValue
来保留来自 IE 预处理的文本:
document.getElementById('test').firstChild.nodeValue = "WELCOME\nhelloworld";
关于javascript - IE 8 浏览器不支持换行符 "\n",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263614/