JQuery hasClass - 为什么在这种情况下它总是返回false?

时间:2014-08-01 08:10:31

标签: javascript jquery html

我有一个带有背景图像的跨度,我希望在点击的加号和减号的背景图像之间切换。我想添加和删除类'open'来执行此操作。我的跨度看起来像这样......

<span class="expand open"></span>

我的JQuery看起来像这样......

$(function() {
    $('.expand').click(function() {
        if ($(this).hasClass('open')) {
            $(this).removeClass('open');
        } else {
            $(this).addClass('open');
        }
    });
});

我得到的行为是它会将类添加为“打开”,但在重复点击后不会再删除它。登录到控制台已显示我的if语句始终评估为false。

我考虑过使用toggleClass但没有这样做,因为一旦这个工作,我打算使用相同的if语句来显示/隐藏内容块。

http://jsfiddle.net/Vz7YL/

EDIT 由于人们专注于我的CSS,我也会提供。 (SASS / SCSS):

.expand {
    background: url(/images/plus-minus-orange.gif) top center no-repeat;
    display: block;
    height: 21px;
    margin: 0 auto;
    width: 22px;
    &.open {
        background: url(/images/plus-minus-orange.gif) bottom center no-repeat;
    }
}

我是否还可以添加跨度IS正确显示且可以单击,并且我无法使用简化版本的代码重新创建问题。

5 个答案:

答案 0 :(得分:1)

你的小提琴适合我。只需在span中添加一些文字即可实际点击span

<span class="expand open">Some Text Here</span>

答案 1 :(得分:1)

Fiddile工作正常。您需要在span中添加一些文本。

enter image description here

答案 2 :(得分:1)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery.min.js" type="text/javascript"></script>
    <style type="text/css">
        .expand {
            background: url('/Images/Icons/greenplus.png') top center no-repeat;
            display: block;
            height: 21px;
            margin: 0 auto;
            width: 22px;
        }
        .open {
            background: url('/Images/Icons/redminus.png') bottom center no-repeat;
        }
    </style>

    <script type="text/javascript">

        $(function () {
            $('.expand').click(function () {
                if ($(this).hasClass('open')) {
                    $(this).removeClass('open');
                } else {
                    $(this).addClass('open');
                }
            });
        });        
    </script>
</head>
    <body>
        <span class="expand open"></span>
    </body>
</html>

这适合我。

答案 3 :(得分:0)

小提琴工作正常。所以问题是点击不适用于背景图片。尝试为span元素添加一些宽度和高度,然后尝试。

喜欢这个

.expand {
background: url(http://upload.wikimedia.org/wikipedia/commons/a/a6/Plus_orange.gif) top center no-repeat;
display: block;
height: 21px;
margin: 0 auto;
width: 22px;

} .open {         background:url(http://www.ilsc.com/course-resource/images/sign-minus-orange.gif)bottom center no-repeat;     } }

http://jsfiddle.net/Vz7YL/4/

答案 4 :(得分:0)

虽然这里的答案都没有为我提供解决方案,但我对其中一条评论的确如此。取代课程&#39; open&#39;为了和替代,例如&#39;扩展&#39;解决了这个问题。谢谢@Doorknob