jquery选择器在IE8中不起作用

mar*_*are 0 javascript jquery jquery-selectors

此代码导致第二行出错($('boxes div.box'))

<script type="text/javascript">

    $(document).ready(function () {
        boxes = $('#boxes div.box');
        images = $('#images > div');
        boxes.each(function (idx) {
            $(this).data('image', images.eq(idx));
        }).hover(
            function () {
                boxes.removeClass('active');
                images.removeClass('active');
                $(this).addClass('active');
                $(this).data('image').addClass('active');
            });
    });

</script>
Run Code Online (Sandbox Code Playgroud)

错误是"对象不支持此属性或方法".同样的页面在Firefox和Chrome中运行良好.

任何人?

Bol*_*ock 10

你需要用var关键字声明变量,否则IE不知道它们来自哪里,所以只会破坏:

var boxes = $('#boxes div.box');
var images = $('#images > div');
Run Code Online (Sandbox Code Playgroud)

  • 据我所知,这是有效的,因为IE对这样的事情要严格得多.在IE中,当脚本遇到错误时它就会停止运行,而在FF和Chrome中,他们设法智能地解决它并继续运行脚本. (3认同)