jquery点击锚点元素强制滚动到顶部? [英] jquery click on anchor element forces scroll to top?

查看:418
本文介绍了jquery点击锚点元素强制滚动到顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery超链接 - href值?文字] [1]

我使用jquery和附加到锚点元素的点击事件运行一个问题。
[1]: jQuery超链接 - href值?这个问题似乎成为一个重复,而接受的答案似乎并没有解决问题。对不起,如果这是坏的礼节。

I am running in to a problem using jquery and a click event attached to an anchor element. [1]: jQuery hyperlinks - href value? "This" SO question seems to be a duplicate, and the accepted answer doesn't seem to solve the problem. Sorry if this is bad SO etiquette.

在我的.ready()函数中,我有:

In my .ready() function I have:

jQuery("#id_of_anchor").click(function(event) { //start function when any update link is clicked
        Function_that_does_ajax();
        });

,我的锚看起来像这样:

and my anchor looks like this:

<a href="#" id="id_of_anchor"> link text </a> 

但是当点击链接时,会根据需要执行ajax函数,但浏览器滚动到页面顶部。不好。

but when the link is clicked, the ajax function is performed as desired, but the browser scrolls to the top of the page. not good.

我已尝试添加:

event.preventDefault(); 

,然后调用我的函数执行ajax,但是没有帮助。
我缺少什么?

before calling my function that does the ajax, but that doesn't help. What am I missing?

澄清

我使用了

return false;
event.preventDefault(); 
event.stopPropagation();

之前和之后我调用我的js ajax函数。它仍然滚动到顶部。

before and after my call to my js ajax function. It still scrolls to the top.

推荐答案

这应该工作,你能澄清

That should work, can you clarify what you mean by "before"? Are you doing this?

jQuery("#id_of_anchor").click(function(event) {
    event.preventDefault();
    Function_that_does_ajax();
});

因为应该工作,如果它不工作,做错了,我们需要看到更多的代码。但是,为了完整起见,你还可以尝试这样:

Because that should work in the sense that if it's not working YOU are doing something wrong and we'd need to see more code. However, for the sake of completeness, you could also try this:

jQuery("#id_of_anchor").click(function() {
    Function_that_does_ajax();
    return false;
});

EDIT

这是一个有效的示例

两个链接使用此代码:

$('#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;
});

正如你可以看到他们工作很好。

And as you can see they are working just fine.

这篇关于jquery点击锚点元素强制滚动到顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆