JQuery:使用:not(.active)选择器,并向所选项添加Active类

时间:2011-05-30 20:23:37

标签: javascript jquery css-selectors

我是Javascript的新手,并且在使用NOT选择器时遇到了一些问题,并且在函数期间添加了一个类,希望这对某人有意义。

我正在创建一个小型图库,我的目标是进行可点击导航,但点击时,活动图像会重定向到另一个页面。

代码如下:

    $("ul#mainGallery li:not(.active) a").click(function(){
      var thisListClass = $(this).parent().attr('class');
         var activeListId = $(this).parent().attr('id');
         var newMarginLeft = (activeListId-3) * -200;
         var animateAction = {};
          animateAction['margin-left'] = newMarginLeft + 'px';
        $("ul#mainGallery").animate(animateAction, 1000);
        $('li.active img').animate({width:'100px', height:'100px'},1000)
        $(this + 'img').animate({width:'300px', height:'300px'},1000)
        $(li.active).removeClass('active');
        $(this).parent().addClass('active');
        return false;

我知道有更好的方法可以做到这一点,但我无法理解它。

编辑:我应该说出问题是什么......

单击活动图像时,它会跟随超链接一切正常。

当点击非活动图像时,它会开始动画,然后(我假设)当添加'active'类时,而不是返回false,它返回true并跟随超链接。

2 个答案:

答案 0 :(得分:2)

要停止默认行为,请使用preventDefault()函数

$("ul#mainGallery li:not(.active) a").click(function(e){
   e.preventDefault(); // will stop the default behaviour
}

详细了解Jquery docs

答案 1 :(得分:2)

每当运行该代码时,您都会将click事件绑定到$("ul#mainGallery li:not(.active) a")(可能是在文档加载时)。在该点处不活动的项将具有该项绑定,并且之后在其他项上更改该类将不会将此事件绑定到它们。您需要更改绑定方式或在函数内部检查项目是否具有该类。

这样的事情:

$("ul#mainGallery li a").click(function(){
if(!$(this).parent().hasClass('active')){


      var thisListClass = $(this).parent().attr('class');
         var activeListId = $(this).parent().attr('id');
         var newMarginLeft = (activeListId-3) * -200;
         var animateAction = {};
          animateAction['margin-left'] = newMarginLeft + 'px';
        $("ul#mainGallery").animate(animateAction, 1000);
        $('li.active img').animate({width:'100px', height:'100px'},1000)
        $(this + 'img').animate({width:'300px', height:'300px'},1000)
        $('li.active').removeClass('active');
        $(this).parent().addClass('active');
        return false;
}

编辑,或者如果您希望继续使用:not和所有内容的相同选择器,请将click功能切换为.live()

相关问题