jQuery:使用:not.active选择器,并将Active类添加到选定的项

问题描述

|| 我是Java的新手,在使用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 \'类时,它返回true并跟随超链接而不是返回false。     

解决方法

        每当代码运行时(可能是在文档加载时),您都将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()
    ,        要停止默认行为,请使用preventDefault()函数
$(\"ul#mainGallery li:not(.active) a\").click(function(e){
   e.preventDefault(); // will stop the default behaviour
}
阅读有关Jquery文档的更多信息