jQuery text() 调用在 Firefox 中保留换行符,但在 IE 中则不然

标签 jquery cross-browser whitespace

我正在做:

alert($("#div").text());

关于这样的事情:

<div id="div">
&lt;div&gt;
Some text
&lt;div&gt;
</div>

为什么要转义内容?因为它有时格式错误,我不希望它干扰或破坏文档的其余部分。

在 FF 中,它显示保留换行符。在 IE7 中则不然。我需要保留空白区域。该内容实际上是在文本区域中进行编辑。

在有人推荐富文本编辑器之前,这段代码并不是真正的 HTML。这是一种自定义方言。

那么如何在 IE 中保留换行符呢?

最佳答案

看来这是我的问题:The Internet Explorer innerHTML Quirk :

However, innerHTML has a problem in Internet Explorer.

The HTML standard requires a transformation on display of content. All kinds and amounts of adjacent whitespace are collapsed into a single space. This is a good thing - just as an example, it allows me to add a lot of line breaks into this source file without having to worry about weird line breaks in the displayed text.

Internet Explorer applies these transformations on assignment to the innerHTML property. This seems like a good idea: it saves a little time during display, because if the in-memory representation is already normalized, then the browser doesn't have to normalize whenever it needs to display the text.

There are exceptions to the normalization rule, though. Notably, these are the <textarea> element, the <pre> element and, in CSS-aware browsers, elements with any value but normal for the white-space property.

Internet Explorer does not respect these special cases. The third makes their optimization a bad idea, because white-space might change at runtime, for example through the DOM. In any case, Internet Explorer will normalize all assignments to the innerHTML property, thus causing the effect demonstrated below.

This text fills the textarea at page load. This, too, contains line breaks and multiple spaces. Formatting is preserved here as well, except that the UA may break lines.

(强调)

事实上,如果我将其更改为:

<div id="div">
<pre>
...
</pre>
</div>

$("#div pre").text()

或者简单地说:

<style type="text/css">
#div { white-space: pre }
</style>

这一切都神奇地起作用。

关于jQuery text() 调用在 Firefox 中保留换行符,但在 IE 中则不然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/656605/

相关文章:

jquery - 如何使用 Jquery 在两个可选字符串之间切换 innerHTML

javascript - 添加类(); jQuery 函数在 Firefox 中不起作用

javascript - 如果图像源(img src)具有特定的类或 ID,则将查询字符串添加到图像源(img src)

css - FireFox 中的 iframe 不遵守 z-index

javascript - 调用 JS 函数之前验证按钮点击

javascript - Internet Explorer 是否支持 arguments.callee.name?

javascript - Angular 2+ 拦截 Command+S 的优雅方式

C#解析字符串拆分

javascript - 包含单个空格的内联 block <span> 未显示

html - CSS - 仅在绝对需要时才在 div 中包装文本