hasClass不起作用

时间:2014-04-22 22:47:00

标签: javascript jquery

我正在使用左右箭头扩展LI的导航系统。

<a href="#" class="icon-arrow-left active"></a>
     <ul>
        <li class="contracted"><a href="#">1</a></li>
        <li class="expanded"><a href="#">2</a></li>
        <li class="activeLesson"><a href="#">3</a></li>
        <li class="expanded"><a href="#">4</a></li>
        <li class="contracted"><a href="#">5</a></li>
    </ul>
<a href="#" class="icon icon-arrow-right active"></a>

当拳头被“扩展”时,&#39; &#39;图标箭头左&#39;应该是“不活跃的”#39;当最后的李被扩展时#39; &#39; icon icon-arrow-right&#39;应该是不活跃的。

我试图使用此功能

 if ($('li:first-child').hasClass('activeLesson')) {
        $('.icon-arrow-left').attr('class','inactive')
        }

这是jsFiddle

2 个答案:

答案 0 :(得分:3)

http://jsfiddle.net/xhP74/2/

$('.arrowButton').find('.icon-arrow-left').click(function () {
    $('.lessonNavigation .expanded.right').attr('class', 'contracted');
    $('.lessonNavigation .activeLesson ').attr('class', 'expanded right');
    $('.lessonNavigation .expanded.left').attr('class', 'activeLesson');
    $('.lessonNavigation .activeLesson').prev().attr('class', 'expanded left');

    if ($('li:first-child').hasClass('activeLesson')) {
        $('.icon-arrow-left').toggleClass('active inactive');
    }
});

您必须将if语句放在事件中,否则只能在文档就绪时调用它。

答案 1 :(得分:2)

将代码移到点击句柄中:

// Count Navigation quantity ==================================            
var count = $('.lessonNavigation li').length;

if (count > 4 && count <= 10) {
    $('.lessonNavigation li').attr('class', 'contracted');
    $('.lessonNavigation li:eq(0)').attr('class', 'expanded left');
    $('.lessonNavigation li:eq(1)').attr('class', 'activeLesson');
    $('.lessonNavigation li:eq(2)').attr('class', 'expanded right');
    $('.lessonNavigation li:eq(3)').attr('class', 'expanded');
}

// ========== Right and Left arrow functions ==================             
$('.arrowButton').find('.icon-arrow-right').click(function () {
    $('.lessonNavigation .expanded.left').attr('class', 'contracted');
    $('.lessonNavigation .activeLesson ').attr('class', 'expanded left');
    $('.lessonNavigation .expanded.right').attr('class', 'activeLesson');
    $('.lessonNavigation .activeLesson + li ').attr('class', 'expanded right');
});

$('.arrowButton').find('.icon-arrow-left').click(function () {
    $('.lessonNavigation .expanded.right').attr('class', 'contracted');
    $('.lessonNavigation .activeLesson ').attr('class', 'expanded right');
    $('.lessonNavigation .expanded.left').attr('class', 'activeLesson');
    $('.lessonNavigation .activeLesson').prev().attr('class', 'expanded left');

    if ($('li:first-child').hasClass('activeLesson')) {
        $('.icon-arrow-left').toggleClass('active inactive');
    }

});

http://jsfiddle.net/xhP74/3/