Jquery: 点击链接后防止窗口滚动

5
我有两个链接,它们在主页上向用户隐藏不同的信息。如果单击其中一个链接,则新信息将显示在屏幕上。问题是,当我单击任何一个链接时,窗口会回到页面顶部。我希望防止这种行为,因为它很烦人。
以下是链接的代码:
<div align="right" id="ajaxIncomingMail"><a href="#" class="incomingMail">Incoming Mail</a></div><div id="ajaxOutgoingMail"><h5><a href="#" class="outgoingMail">Outgoing Mail</a></h5></div>

这里是jQuery的代码:

        $(function(){
      $("a.incomingMail").click(function(e){
            e.preventDefault();
            $("#ajaxMailShowContentOutbox").hide();
            $("#ajaxMailShowContentInbox").fadeIn("slow");
        });

        $("a.outgoingMail").click(function(e){
            e.preventDefault();
            $("#ajaxMailShowContentInbox").hide();
            $("#ajaxMailShowContentOutbox").fadeIn("slow");
        });
        return false;
    });

我在这里使用preventDefault(),但它仍然不起作用!?我还尝试了return false,但也没有起作用。我不知道是否重要,但展示的信息是通过php从数据库中提取的。当我点击链接时,如何停止滚动?


e.preventDefault()应该可以解决这个问题。页面是向顶部滚动还是由于页面中的内容发生变化而滚动? - partkyle
我同意Kevin Gurney的观点 - 如果链接实际上是在DOM加载后和javascript已经执行之后添加到页面中的话,他可能需要使用.live()。 - Pandincus
partkyle,滚动是因为页面上的内容正在改变。不,链接本身并不会改变——只有内容会改变,但链接不会改变。 - Johny
您的问题解决了吗?请查看此链接并告诉我。http://jsfiddle.net/tsegay/fWyxM/ - tkt986
3个回答

13

在实际的jQuery点击事件中,return false;不应该在外部而是应该在内部吗?

编辑

    $(function(){
  $("a.incomingMail").click(function(e){
        e.preventDefault();
        $("#ajaxMailShowContentOutbox").hide();
        $("#ajaxMailShowContentInbox").fadeIn("slow");
        return false;
    });

    $("a.outgoingMail").click(function(e){
        e.preventDefault();
        $("#ajaxMailShowContentInbox").hide();
        $("#ajaxMailShowContentOutbox").fadeIn("slow");
        return false;
    });

});

我在click事件中有返回值,但我认为这与我如何操作我的div和类有关。 - Johny
能给我演示一下吗?我一直将上面的代码理解为:.click(function(){ //在点击事件内部对吧? return false; }); //现在是在点击函数外部 - Johny
我的错。是的,在我的原始帖子中,我在 click 函数之外。不过我已经纠正了。谢谢。哈哈,我真傻! - Johny

5

您可能会在a标签中使用href='#',将其更改为href='###'即可停止滚动。


3
您可能想尝试:
$("a.incomingMail").live("click", function(e) {
    e.preventDefault();
    $("#ajaxMailShowContentOutbox").hide();
    $("#ajaxMailShowContentInbox").fadeIn("slow");
});

并且

$("a.outgoingMail").live("click", function(e) {
    e.preventDefault();
    $("#ajaxMailShowContentInbox").hide();
    $("#ajaxMailShowContentOutbox").fadeIn("slow");
});

如果您的信息是从数据库中提取的,建议使用 "instead of .click",因为使用 .click() 将单击事件处理程序绑定到链接时,事件处理程序仅适用于已在页面上加载的元素,而不适用于稍后从数据库加载的元素。

还是不行 : ( 我需要哪个版本的jQuery才能使用live()方法? - Johny
刚刚检查了一下,我有jQuery V1.4.1,所以那不应该是问题所在。我一定是做错了什么。 - Johny
很奇怪。我修改了我的代码,不从数据库中提取信息,而是使用静态内容 - 但问题依旧。 - Johny
这有点奇怪。虽然在JSFiddle中很难看出它正在向上滚动。也许你可以让内容出现在弹出框中,而不是在单击出站或入站邮件时仅填充先前内容的位置。 - Kevin Gurney
这是一个可能的解决方案,但我不想用弹出窗口过度。我已经为其他功能有其他的弹出窗口了。 - Johny
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接