对象不支持属性或方法“removeClass”

3
我正在尝试使用removeClass和addClass来更改图像的样式。
    <div id="Pic_Viewer">
        <div id="Main_Pic_Viewer">
                <div class="Not_Selected" >
                    <img src='#' alt="PicURL_1" />
                </div>
                <div class="Not_Selected" >
                    <img src='#' alt="PicURL_2" />
                </div>
        </div>
        <div id="Small_Pic_Viewer">
            <ul>
                <li>
                    <img class="Small_Pic" src'#' alt="PicURL_1" />
                </li>
                <li>
                    <img class="Small_Pic" src='#' alt="PicURL_2" />
                </li>
            </ul>
        </div>
    </div>

我尝试过在 div 中包含 #Main_Pic_Viewer img 和不包含它来进行这个操作。
js:
$('#Small_Pic_Viewer ul li').click(
        function () {
            var ThisLI = this.firstElementChild.alt;
            var BigImgDiv = $('#Main_Pic_Viewer div');
            var CurDiv;

            for (var i = 0, l = BigImgDiv.length; i < l; i++) {
                CurDiv = BigImgDiv[i];
                if (BigImgDiv[i].children[0].alt === ThisLI) {
                    CurDiv.removeClass('Not_Selected').addClass('Selected');
                } else {
                    CurDiv.removeClass('Selected');
                };
            };
        }
    );

不确定为什么会出现这个错误消息,因为removeClass() 在其他方法中运行正常。

2
因为它不是一个jQuery对象,所以只需执行CurDiv = $(BigImgDiv[i]);即可。 - Ohgodwhy
非常感谢大家,完全回答了我的问题。 - DirtyRedz
2个回答

6

在jQuery对象中使用数字索引时,您将获得原始的DOM元素,而不是jQuery封装器。

只需再次用jQuery函数包装即可:

// ...

CurDiv = $( BigImgDiv[i] );

// ...

@Andreas在评论中提到的另一种解决方案是使用eq()方法,这可能是更好的方法:

// ...

CurDiv = BigImgDiv.eq(i);

// ...

3
为什么要将DOM元素解封再立即包装成jQuery对象?使用.eq()代替即可。 - Andreas

0
试一下这个:http://jsfiddle.net/Yx5c8/1/
$('#Small_Pic_Viewer ul li').click(function () {
    var ThisLI = this.firstElementChild.alt;
    $('#Main_Pic_Viewer div').each(function () {
        if (this.children[0].alt === ThisLI) {
            $(this).removeClass('Not_Selected').addClass('Selected');
        } else {
            $(this).removeClass('Selected');
        }
    });
});

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