尝试使用JS在click事件上应用类

时间:2014-06-20 20:21:06

标签: javascript jquery

我是JavaScript的新手,并且已经使用了关于如何从这里切换类的主要帖子:Change an element's class with JavaScript但由于某种原因我的代码没有像我期望的那样执行。代码放在HTML文件的底部。

<script>
$(document).ready(function () {

$('.arrow').addEventListener('click', function() {
if (this.hasClass('glyphicon-chevron-right')) {
    this.addClass('glyphicon-chevron-left');
    this.removeClass('glyphicon-chevron-right');
    }

if (this.hasClass('glyphicon-chevron-left')) {
    this.addClass('glyphicon-chevron-right');
    this.removeClass('glyphicon-chevron-left');
    }
}, false);

});
</script>

2 个答案:

答案 0 :(得分:4)

设置点击监听器并使用 .toggleClass() 代替那些if子句:

$('.arrow').on('click', function() {
    $(this).toggleClass('glyphicon-chevron-right');
    $(this).toggleClass('glyphicon-chevron-left');
});

或者更简洁

$('.arrow').on('click', function() {
    $(this).toggleClass('glyphicon-chevron-right glyphicon-chevron-left');
});

答案 1 :(得分:2)

只需使用jQuery点击事件。

$('.arrow').click(function() {
    if (this.hasClass('glyphicon-chevron-right')) {
        this.addClass('glyphicon-chevron-left');
        this.removeClass('glyphicon-chevron-right');
    }
    if (this.hasClass('glyphicon-chevron-left')) {
        this.addClass('glyphicon-chevron-right');
        this.removeClass('glyphicon-chevron-left');
    }
});

如果要使用事件侦听器专门添加事件,则可能必须选择实际元素而不是jQuery对象:$('.arrow')[0]