jQuery('body').text() 在不同的浏览器中给出不同的答案
我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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.
其中一些可能与浏览器放置正文外部但 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.
由于不同的浏览器有不同的行为方式,我建议:
这应该产生一致的结果。
As different browsers behave in different ways, I suggest:
This should produce consistent results.