jQuery hyperlinks - href value?文字][1]
我在使用 jquery 和附加到 anchor 元素的单击事件时遇到问题。 [1]:jQuery hyperlinks - href value? “这个”SO问题似乎是重复的,并且接受的答案似乎没有解决问题。抱歉,如果这是不好的礼仪。
在我的 .ready() 函数中,我有:
jQuery("#id_of_anchor").click(function(event) { //start function when any update link is clicked
Function_that_does_ajax();
});
我的 anchor 看起来像这样:
<a href="#" id="id_of_anchor"> link text </a>
但是当点击链接时,ajax函数按照需要执行,但是浏览器滚动到页面顶部。不好。
我尝试添加:
event.preventDefault();
在调用我执行ajax的函数之前,但这没有帮助。 我错过了什么?
澄清
我用过所有的组合
return false;
event.preventDefault();
event.stopPropagation();
调用 js ajax 函数之前和之后。它仍然滚动到顶部。
最佳答案
这应该可行,你能澄清一下“之前”的意思吗?你在做这个吗?
jQuery("#id_of_anchor").click(function(event) {
event.preventDefault();
Function_that_does_ajax();
});
因为应该可以工作,如果它不起作用,那么你就做错了什么,我们需要查看更多代码。但是,为了完整起见,您也可以尝试以下操作:
jQuery("#id_of_anchor").click(function() {
Function_that_does_ajax();
return false;
});
编辑
Here is an example of this working .
这两个链接使用此代码:
$('#test').click(function(event) {
event.preventDefault();
$(this).html('and I didnt scroll to the top!');
});
$('#test2').click(function(event) {
$(this).html('and I didnt scroll to the top!');
return false;
});
正如您所看到的,它们工作得很好。
关于jquery点击 anchor 元素强制滚动到顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1061580/