gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:13:07 24 4
gpt4 key购买 nike

我正在做:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com