【问题标题】:how to stop a hashtag's default click behaviour? [duplicate]如何停止主题标签的默认点击行为? [复制]
【发布时间】:2023-03-13 03:40:01
【问题描述】:

可能重复:
Stop default hashtag behavior with jquery

我在链接上有一些 jquery 代码,它使用 .load() 将 DIV 加载到页面中,它还在 url 中添加了一个标签以用于分页/书签目的;我想要做的是在单击链接时阻止页面跳转到 div。

$('#jqNav li a').click(function(){

    if($(this).parent().is(".nav1")){ $('.landing .main .nav ul').css({ "background-position" : "0 -50px" });} 
    else if($(this).parent().is(".nav2")) {    $('.landing .main .nav ul').css({ "background-position" : "0 -100px" });}
    else if($(this).parent().is(".nav3")) {    $('.landing .main .nav ul').css({ "background-position" : "0 -150px" });}
    else if($(this).parent().is(".nav4")) {    $('.landing .main .nav ul').css({ "background-position" : "0 -200px" });};


    stopAnim = true;
    $page = $(this).attr('href');
    var $hashTag = $(this).attr('name');
    window.location = "#" + $hashTag;
    loadData();
    e.preventdefault();
    return false;

});

【问题讨论】:

  • @Michael Irigoyen 我已经在我的代码中返回 false 这是您链接的答案,它仍然通过了问题,请注意 e.preventdefault();刚刚添加。

标签: jquery hashtag


【解决方案1】:

尝试在链接点击上使用e.preventDefault();

尝试使用$(window).scrollTop(0);防止#影响页面

【讨论】:

  • 这正是我所需要的,感谢尼尔!
【解决方案2】:

您可以为此使用e.preventDefault()

http://api.jquery.com/event.preventDefault/

或使用:

return false;

preventDefault()stopPropagation() 两者都有什么作用

http://api.jquery.com/event.stopPropagation/

编辑

不要以为你想做的事就可以做到。因为能够在不转到该 URL 的情况下更改页面的 URL 是不安全的。

例如,您可以将 URL 更改为银行的 URL,让用户认为您的页面代表银行。

也许它仅在添加哈希时有效,因此您可以尝试以下方法(尚未测试,很可能不起作用):

window.location.hash = $hashTag;
return false;

EDIT2

我知道我刚刚告诉过你它不起作用,但是我偶然发现了这篇关于 SO 的帖子,它使用 HTML5 来做你想做的事:

Is there a way to change the browser's address bar without refreshing the page?

再次未测试:)

【讨论】:

  • 我的代码已经有返回默认值了,但是好像会跳转,否则代码见OP;
  • 谢谢,这很有用,但我不会重建整个东西,所以尼尔斯的回答被证明更适合我的需要。
【解决方案3】:

您可以使用return false; 作为点击处理程序中的最后一条语句。或者同时使用event.preventDefault()event.stopPropagation()return false 等于它们一起,防止该元素的默认行为防止事件通过 DOM 冒泡)。

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多