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

前端之家收集整理的这篇文章主要介绍了jQuery text()调用在Firefox中保留换行符,但不保留在IE中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在做:
alert($("#div").text());

就像这样:

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

为什么逃脱的内容?因为它有时是畸形的,我不希望它干扰或打破文档的其余部分.

在FF中,它显示保留换行符.在IE7它没有.我需要保留白色的空间.该内容实际上是在一个textarea进行编辑.

在任何人推荐一个富文本编辑器之前,这段代码并不是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相关文章