Javascript没有在地址栏中添加id

Javascript not adding id in address bar

本文关键字:添加 id 地址栏 Javascript      更新时间:2023-09-26

由于某些原因,这个javascript不会将被点击元素的id添加到地址栏中。它将正确地执行其他操作。

的格式如下:http://jsfiddle.net/4x7La64s/

例如,如果我点击#introduction我想让它在地址栏中显示它的id像这样:example.com/page.php/#introduction

根据您的代码,在执行以下操作后:

e.preventDefault();

你可以这样做:

var hash = jQuery(this).attr("href"); //Your clicked link
if (window.history && window.history.pushState) {
  history.pushState(null, null, 'hash'); // This won't make the page jump to the id
} else {
  location.hash = hash; //This will be the fallback for old browsers and this will make the page jump to that id
}

preventDefault,顾名思义,防止默认动作发生;在锚的情况下,导航到新的URL。

技术定义可以在Mozilla的开发者网络(https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault):

)上找到。

取消可取消的事件,但不停止事件的进一步传播。

由于您正在取消事件,浏览器不做任何事情(例如滚动到元素)。

您可以添加以下代码而无需更改其他任何内容:

var hash = this.hash;
if ('history' in window && history.pushState) {
    // Add a new state in the browser's history. Does not scroll to the element
    // See https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
    history.pushState('', '', hash);
} else {
    // Fallback for old browsers (mainly IE<9). Scrolls to the element
    location.hash = hash;
}

代码在浏览器的历史记录中添加了一个新条目。

请看https://jsfiddle.net/toothbrush7777777/108d4356/的例子

删除默认防止功能:

e.preventDefault();