简体   繁体   English

如何在href链接上使用js参数和锚点(同一页面)

[英]How to use js parameter and anchor(same page) on a href link

Every time I click an <a> element with an anchor AND a JavaScript parameter, the URL doesn't change, the page just leads me to the anchor element.每次我单击带有锚点和 JavaScript 参数的<a>元素时,URL 不会改变,页面只是将我引导到锚点元素。 For example, when I'm on "website.com" and I click this hyperlink:例如,当我在“website.com”上并单击此超链接时:

<a href="website.com/?par=123#anchor">TEST</a>

The page will scroll to the #anchor element but the URL will still be "website.com", so the JS parameter doesn't get any value.页面将滚动到#anchor 元素,但 URL 仍将是“website.com”,因此 JS 参数没有获得任何值。 I tried to replace the code with this:我试图用这个替换代码:

<a href="website.com/?par=123#anchor" onclick="window.location.reload(true)">

And the page reloads, but it only reloads after scrolling to the #anchor element and it still keeps on "website.com", so no success.并且页面重新加载,但它仅在滚动到#anchor 元素后重新加载并且它仍然保留在“website.com”上,所以没有成功。

This is the whole purpose of URL hashes .这是URL hashes的全部目的。 It was initially designed to scroll to a particular id in the DOM and was also used by some SPA (Single Page Application) frameworks before the History API existed, as a solution to represent a JavaScript state in the URL. It was initially designed to scroll to a particular id in the DOM and was also used by some SPA (Single Page Application) frameworks before the History API existed , as a solution to represent a JavaScript state in the URL.

As it represents a state of the web page in the browser , it's never sent to the server so the browser doesn't send the request again when it changes because the current URL (and thus the server-side resource) is considered unchanged.由于它代表浏览器中 web 页面的 state ,因此它从未发送到服务器,因此浏览器在更改时不会再次发送请求,因为当前的 ZE6B391A8D2C4D459702A23A8B658 资源被视为未更改(因此服务器端资源)。

If you want to execute JavaScript code in reaction to the hash change event, you can do like this:如果您想执行 JavaScript 代码以响应 hash 更改事件,您可以这样做:

 window.addEventListener('hashchange', () => console.log(window.location.hash));
 <a href="#foo">Foo</a> <a href="#bar">Bar</a>

You can use par='123#anchor' instead par=123#anchor like this code and it works.您可以使用par='123#anchor'代替par=123#anchor ,就像这段代码一样,它可以工作。

   <a href="website.com/?par='123#anchor'">TEST</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM