我将假设.galleryButtonLeft
元素与它们的href
属性的链接设置为散列(#
)。无论是return false
或event.preventDefault()
取消链接(S)的默认行为:
$(function() {
$(".galleryButtonLeft").mousedown(function(){
$("#theGallery").animate({
marginLeft: "-=300px"//notice I removed the trailing comma here, it'll come back to haunt you if you don't (some browsers throw errors for these)
}, 1000);
}).click(false);//this returns false for any click event for the/these element(s), stopping the default behavior of the element(s)
});
返回false
内一个jQuery事件处理的是同样的事情,呼吁event.preventDefault()
和event.stopPropagation()
。
如果你想使用event.preventDefault()
而不是返回false
,那么你必须传递在event
对象在匿名函数(事件处理程序):
$(function() {
$(".galleryButtonLeft").mousedown(function(){
event.preventDefault();
$("#theGallery").animate({
marginLeft: "-=300px"//notice I removed the trailing comma here, it'll come back to haunt you if you don't (some browsers throw errors for these)
}, 1000);
}).click(function (event) {
event.preventDefault();
});
});
注意,您可以在事件的任何地方拨打event.preventDefault()
处理程序,但返回false
必须是最后一次调用,因为它会停止执行事件处理程序。
小问题:'300px'后面会出现一个尾随的逗号,这会在某些版本的IE中导致错误。 – Sparky 2012-02-10 18:52:23
您还应该提供相关位的HTML代码。 – Sparky 2012-02-10 18:53:19
您可能在按钮内部有一个'href =“#”',当点击它时,会将您带回到页面的顶部。请参阅下面的@ gion_13回答。 – Sparky 2012-02-10 18:56:56