我在 Internet Explorer 8 中发现了这个问题,但在 Safari 或 Firefox 中没有。到目前为止,我还没有在其他 IE 版本中测试过。
我正在开发自己的 jQuery 插件,对于这个问题,我将其简化为两行相关内容。
在 IE 8 中,使用下面的代码,$('title').text()
什么都不做。 docTitle
是空白的,因为 title
是空白的,就好像 <title>
的 jQuery 选择器一样, $('title')
不管用。 (再一次,AFAIK,这只是在 IE 8 中)
(function ($) {
$.fn.myPlugin = function (options) {
var title = $('title').text(),
docTitle = escape(title);
};
})(jQuery);
http://jsfiddle.net/sparky672/YMBQ2/
但是,使用下面的纯 JavaScript 代码,document.title
在包括 IE 8 在内的所有方面都运行良好...
(function ($) {
$.fn.myPlugin = function (options) {
var docTitle = escape(document.title);
};
})(jQuery);
编辑:
这段代码在插件中并不重要。
在 IE 8 中的结果与此相同...
$(document).ready(function () {
var title = $('title').text();
alert(title);
});
澄清一下,我并不是坚持要使用它。事实上,我通过简单地使用 document.title
修复了我的插件反而。 如果一开始不清楚,我只是想问为什么这在 IE 8 中不起作用。
谁能解释原因,或者我可能在这里犯了什么愚蠢的错误?
编辑 2:
这里有一些关于这个问题的 jQuery Bug 报告
http://bugs.jquery.com/ticket/7025
http://bugs.jquery.com/ticket/5881
http://bugs.jquery.com/ticket/2755
还有许多其他人报告了同样的事情。官方回应是声明,“document.title
是唯一可靠的跨浏览器方式,应该改用” 并且票证已关闭。好了。
最佳答案
我猜 jQuery 遍历所有 TextNode 并连接它的 nodeValue。 IE 以不同于其他浏览器的方式存储此值。
var title = document.getElementsByTagName('title')[ 0 ];
title.firstChild // This would be the Text-Object with the characterdata of the title
// Firefox: [object Text]
// IE: null
这应该是您无法使用 jQuery.text()
获取 textContent 的原因。 title.text
似乎是跨浏览器组件。我只在 IE 7 和 Firefox 3.6 中测试过它,但 you can check the other browser如果你喜欢。但为什么不使用 document.title
呢?
关于javascript - 无法使用 jQuery (IE 8) 访问文档的标题元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7897005/