IE 8:对象不支持属性或方法“getElementsByClassName”。

10

我正在使用 Diapo 滑块,它似乎在除了 Internet Explorer 8 之外的所有其他浏览器中都可以正常工作。

在运行 ie8 调试模式后,我收到以下错误:

SCRIPT438: 对象不支持“getElementsByClassName”属性或方法 prototype.js, 第5988行第5个字符

return function(className, parentElement) {
    return $(parentElement || document.body).getElementsByClassName(className);
  };

SCRIPT438: 对象不支持 'fireEvent' 属性或方法 prototype.js,第5736行字符7

if (document.createEvent)
      element.dispatchEvent(event);
    else
      element.fireEvent(event.eventType, event);

    return Event.extend(event);

我正在Magento平台上运行这个滑块,似乎问题出在prototype脚本上。它使用的prototype版本是1.7,所以不能通过升级脚本来解决问题。

注意:虽然我在IE9中没有显示问题,但我得到了以下错误:

SCRIPT438: 对象不支持“dispatchEvent”属性或方法 prototype.js,第5734行第7个字符

if (document.createEvent)
      element.dispatchEvent(event);
    else
      element.fireEvent(event.eventType, event);

    return Event.extend(event);

这些是 Diapo 滑块所需的脚本,在头部使用 script 标签加载。我不确定,但也许其中一些脚本与现有的脚本发生了冲突:

<script type='text/javascript' src='http://www.pixedelic.com/plugins/diapo/scripts/jquery.min.js'></script>
<script type='text/javascript' src='http://www.pixedelic.com/plugins/diapo/jquery.mobile-1.0rc2.customized.min.js'></script>
<script type='text/javascript' src='http://www.pixedelic.com/plugins/diapo/jquery.easing.1.3.js'></script>
<script type='text/javascript' src='http://www.pixedelic.com/plugins/diapo/jquery.hoverIntent.minified.js'></script>
<script type='text/javascript' src='http://www.pixedelic.com/plugins/diapo/scripts/diapo.js'></script>
1个回答

18

IE8不支持getElementsByClassName。然而,它支持 querySelectorAll。因此,我建议使用querySelectorAll编写一个polyfill。

document.getElementsByClassName('foo')

转换成

document.querySelectorAll('.foo'); // Prefixed dot.

请注意,Prototype.js 不再支持使用getElementsByClassName,而推荐使用$$Element#select
IE8的快速修复方法:
<!--[if IE 8]><script>
document.getElementsByClassName = 
Element.prototype.getElementsByClassName = function(class_names) {
    // Turn input in a string, prefix space for later space-dot substitution
    class_names = (' ' + class_names)
        // Escape special characters
        .replace(/[~!@$%^&*()_+\-=,./';:"?><[\]{}|`#]/g, '\\$&')
        // Normalize whitespace, right-trim
        .replace(/\s*(\s|$)/g, '$1')
        // Replace spaces with dots for querySelectorAll
        .replace(/\s/g, '.');
    return this.querySelectorAll(class_names);
};
</script><![endif]-->

注意:

  • 它支持多个类名。
  • 它不支持空的('')类名。如果需要,添加支持这些类名是微不足道的。

演示:http://jsfiddle.net/HL4FL/21/


谢谢Rob的回复,但我该如何应用这个修复方法呢?我已经更新了我的帖子,并提供了有关使用的脚本更相关的详细信息,请告诉我这是否有所帮助。非常感谢! - gdinari
你在同一个页面上同时使用了jQuery和Prototype.js。它们之间有冲突的可能吗?Diapo并不使用Prototype.js,但你仍然会收到与Prototype.js相关的错误信息。 - Rob W
是的,原型脚本是Magento平台的一部分,因此默认情况下已上传...我可以尝试仅针对主页禁用它,但我也对您的polyfill解决方案感兴趣。 - gdinari
@gdinari 请查看更新后的答案以获取polyfill。这必须在Prototype.js之前包含。 - Rob W
太好了!谢谢你,Rob。为了这个修复,我费尽心思的日子是值得的。再次感谢。 - gdinari
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接