jquery切换:点击链接跳转回页面顶部 [英] jquery toggle: clicking on link jumps back to top of the page
问题描述
我创建了一个jquery切换,但当我点击链接打开一个div时,它会跳转到页面顶部。我该如何解决这个问题?
I created a jquery toggle, but when I click the link to open a div it will jump to the top of the page. how can I fix this?
我知道我可以用其他东西替换链接但是我需要向用户说明它是一个链接并且他们可以点击在它上面。
I know I could replace the link with something else but I need to make it clear to the users that it's a link and that they can click on it.
推荐答案
添加返回false;
到结尾单击链接时运行的代码。
Add return false;
to the end of the code that runs when you click the link.
$('a.myLink').toggle(function() {
// run my code
return false;
});
或者,您可以获取事件
对象,并致电 .preventDefault()
。
Alternatively, you can grab the event
object, and call .preventDefault()
.
$('a.myLink').toggle(function(event) {
event.preventDefault();
// run my code
});
这两种方法都会禁用链接的默认行为。
Both of these methods disable the default behavior of the link.
第一个也会阻止事件冒泡,所以只有在你不需要利用事件冒泡时才使用它。
The first one will also prevent the event from bubbling, so use it only if you have no need to utilize the event bubbling.
这篇关于jquery切换:点击链接跳转回页面顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!