href =“#"转到页面顶部-预防吗? [英] href="#" Going to Top of Page - Prevent?

查看:110
本文介绍了href =“#"转到页面顶部-预防吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有jQuery功能的页面.页面上的HTML如下所示:

I have a page with some jQuery functions. The HTML on the page looks like so:

<a href="#" class="service">Open</a>

当我单击打开"按钮时,一个隐藏的面板滑出. jQuery本身运行良好,但是当我单击按钮时,它也将我带到页面顶部.

When I click the Open button a hidden panel slides out. The jQuery itself works great however when I click the button it also takes me to the top of the page.

这是默认行为吗?如何防止每个href="#"将我带到页面顶部.

Is this the defualt behavior and how do I prevent every href="#" from taking me to the top of the page.

注意:我可以添加ID并告诉href定向到该ID.出于各种原因,我不想这样做(包括添加不必要的代码).

Note: I could add id's and tell the href to direct to that ID. I do not want to do that for various reasons (including adding unnecessary code).

推荐答案

在事件处理程序中,添加e.preventDefault();(假设e是保存事件的变量的名称):

In your event handler, add e.preventDefault(); (assuming e is the name of the variable holding the event):

$('.service').click(function(e) {
    e.preventDefault();
});

这篇关于href =“#"转到页面顶部-预防吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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