我是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;
我知道可能有更好的方法可以做到这一点,但我无法理解
编辑:我可能应该说问题出在哪里…
单击活动图像时,它会跟随超链接,一切正常。
当单击非活动图像时,它开始动画,然后(我假设)当添加"活动"类时,它不会返回false,而是返回true并跟随超链接。
每当代码运行时(可能是在文档加载时),您都会将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;
}
EDIT,或者如果您希望继续使用:not
和所有内容的相同选择器,则将click
功能切换到.live()
要停止默认行为,请使用preventDefault()函数
$("ul#mainGallery li:not(.active) a").click(function(e){
e.preventDefault(); // will stop the default behaviour
}
阅读Jquery文档的更多信息