jQuery('body').text() 在不同的浏览器中给出不同的答案

发布于 2024-09-01 23:57:19 字数 898 浏览 3 评论 0原文

我的 HTML 看起来像这样:

<html>
<head>
   <title>Test</title>
   <script type="text/javascript" src="jQuery.js"></script>
   <script type="text/javascript">
      function init() 
  {
         var text = jQuery('body').text();
         alert('length = ' + text.length);
      }
   </script>
</head>
<body onload="init()">0123456789</body>
</html>

当我在 Firefox 中加载它时,长度报告为 10。但是,在 Chrome 中,它是 11,因为它认为“9”后面有一个换行符。在 IE 中也是 11,但最后一个字符是转义符。同时,Opera 认为有 12 个字符,最后两个是 CR LF。

如果我更改 body 元素以包含 span:

<body onload="init()"><span>0123456789</span></body>

并且 jQuery 调用为:,

var text = jQuery('body span').text();

则所有浏览器都同意长度为 10。

显然是 body 元素导致了问题,但任何人都可以准确解释为什么会发生这种情况吗?我特别惊讶,因为优秀的 jQuery 通常是独立于浏览器的。

My HTML looks like this:

<html>
<head>
   <title>Test</title>
   <script type="text/javascript" src="jQuery.js"></script>
   <script type="text/javascript">
      function init() 
  {
         var text = jQuery('body').text();
         alert('length = ' + text.length);
      }
   </script>
</head>
<body onload="init()">0123456789</body>
</html>

When I load this in Firefox, the length is reported as 10. However, in Chrome it's 11 because it thinks there's a linefeed after the '9'. In IE it's also 11, but the last character is an escape. Meanwhile, Opera thinks there are 12 characters, with the last two being CR LF.

If I change the body element to include a span:

<body onload="init()"><span>0123456789</span></body>

and the jQuery call to:

var text = jQuery('body span').text();

then all the browsers agree that the length is 10.

Clearly it's the body element that's causing the issue, but can anyone explain exactly why this is happening? I'm particularly surprised because the excellent jQuery is normally browser-independent.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最丧也最甜 2024-09-08 23:57:19

Opera 在 BODY 或 HTML 关闭标记后获取换行符,并将它们添加到 BODY 内容 AFAIK 中。这可能就是额外的 CR LF 的来源。

Opera takes newlines after BODY or HTML close tag and adds them to BODY contents AFAIK. This is probably where the extra CR LF comes from.

许久 2024-09-08 23:57:19

其中一些可能与浏览器放置正文外部但 HTML 内部的文本或 HTML 外部的文本的不同行为有关。如果自 HTML5 解析器登陆以来 Firefox nightlies 中的情况发生变化,我不会感到惊讶。

Some of this may have to do with different behavior for where browsers put the text that's outside body but inside HTML, or the text that's outside of HTML. It wouldn't surprise me if that's changed in Firefox nightlies since the HTML5 parser landed.

一抹苦笑 2024-09-08 23:57:19

由于不同的浏览器有不同的行为方式,我建议:

jQuery('iframe').contents().find('body').text().trim();

这应该产生一致的结果。

As different browsers behave in different ways, I suggest:

jQuery('iframe').contents().find('body').text().trim();

This should produce consistent results.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文