使用 html 锚点强制页面重新加载 (#) - HTML & JS

发布于 2024-08-27 10:29:53 字数 256 浏览 8 评论 0原文

假设我正在访问一个名为 /example#myanchor1 的页面,其中 myanchor 是该页面中的锚点。 我想链接到 /example#myanchor2,但在执行此操作时会强制页面重新加载。

原因是我在页面加载时运行 js 来检测 url 中的锚点。 但这里的问题(通常是预期的行为)是,浏览器只是将我发送到页面上的特定锚点,而无需重新加载页面。

我该怎么做呢? JS 还可以。

Say I'm on a page called /example#myanchor1 where myanchor is an anchor in the page.
I'd like to link to /example#myanchor2, but force the page to reload while doing so.

The reason is that I run js to detect the anchor from the url at the page load.
The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.

How would I go about doing so? JS is OK.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

乜一 2024-09-03 10:29:53

我建议监视 URL 中的锚点以避免重新加载,这几乎就是使用锚点进行控制流的要点。但仍然如此。我想说使用简单的锚链接强制重新加载的最简单方法是使用

<a href="?dummy=$random#myanchor2"></a>

where 代替 $random 插入随机数(假设“dummy”不被解释为服务器端)。我确信有一种方法可以在设置锚点后重新加载页面,但这可能比简单地对设置的锚点做出反应并执行此时所需的操作更困难。

话又说回来,如果您以这种方式重新加载页面,您只需将 myanchor2 作为查询参数即可,然后在服务器端渲染您的内容。

编辑
请注意,上面的链接在所有情况下都会重新加载,如果您只需要在尚未进入页面时重新加载,则需要让虚拟变量更具可预测性,就像这样,

<a href="?dummy=myanchor2#myanchor2"></a>

我仍然建议只监视哈希值。

I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use

<a href="?dummy=$random#myanchor2"></a>

where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.

Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.

Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so

<a href="?dummy=myanchor2#myanchor2"></a>

I would still recommend just monitoring the hash though.

你的他你的她 2024-09-03 10:29:53

就这么简单

<a href="#hardcore" onclick="location.reload()">#hardcore</a>

一个例子

Simple like that

<a href="#hardcore" onclick="location.reload()">#hardcore</a>

an example

她比我温柔 2024-09-03 10:29:53

另一种方法是设置 url,并使用 window.location.reload() 强制重新加载。

<a href="/example#myanchor2" 
    onclick="setTimeout(location.reload.bind(location), 1)">
</a>

基本上,setTimeout 会延迟重新加载。由于 onclick 中没有 return false,因此执行了 href。然后,href 会更改 url,并且只有在这之后才会重新加载页面。

不需要 jQuery,而且很简单。

Another way to do that is to set the url, and use window.location.reload() to force the reload.

<a href="/example#myanchor2" 
    onclick="setTimeout(location.reload.bind(location), 1)">
</a>

Basically, the setTimeout delays the reload. As there is no return false in the onclick, the href is performed. The url is then changed by the href and only after that is the page reloaded.

No need for jQuery, and it is trivial.

〆凄凉。 2024-09-03 10:29:53

我最喜欢的解决方案,受到 另一个答案 的启发,是:

<a href="#myanchor2" onclick="location.hash='myanchor2'; location.reload();">myanchor2</a>

href 链接将不会被关注,因此您可以使用您自己的偏好,例如:"""#"

尽管我喜欢接受的答案,但我发现这更优雅,因为它没有引入外部参数。 @Qwerty 和 @Stilltorik 的答案都导致哈希在我重新加载后消失。

My favorite solution, inspired by another answer is:

<a href="#myanchor2" onclick="location.hash='myanchor2'; location.reload();">myanchor2</a>

href link will not be followed so you can use your own preference, for example: "" or "#".

Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both @Qwerty's and @Stilltorik's answers were causing the hash to disappear after reload for me.

眼眸 2024-09-03 10:29:53

如果您总是要不断重新加载页面,那么使用客户端 JS 有什么意义呢?即使页面没有重新加载,监视哈希值的更改可能是一个更好的主意。

此页面有一个哈希监视器库和一个与之配套的 jQuery 插件。

如果您确实想重新加载页面,为什么不使用查询字符串 (?foo) 而不是哈希呢?

What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.

This page has a hash monitor library and a jQuery plugin to go with it.

If you really want to reload the page, why not use a query string (?foo) instead of a hash?

也只是曾经 2024-09-03 10:29:53

尚未提及的另一个选项是将事件侦听器(例如使用 jQuery )绑定到您关心的链接(可能是全部,也可能不是),并让侦听器调用您使用的任何函数。

评论后编辑

例如,您的 HTML 中可能包含以下代码:

<a href="example#myanchor1" class="myHash">example1</a>
<a href="example#myanchor2" class="myHash">example2</a>
<a href="example#myanchor3" class="myHash">example3</a>

然后,您可以添加以下代码来绑定和响应链接:

<script type="text/javascript">
    $('a.myHash').click(function(e) {
        e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
        var linkHref = $(this).attr('href'); // Grab the URL from the link
        if (linkHref.indexOf("#") != -1) { // Check that there's a # character
            var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
            myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
            alert(hash); // Just for fun.
        }
    });
</script>

请注意,我使用的是 jQuery 类选择器 选择我想要“监视”的链接,但您可以使用任何 选择器 你想要的。

根据现有代码的工作方式,您可能需要修改传递给它的方式/内容(也许您需要构建一个包含新哈希的完整 URL 并将其传递 - 例如 http://www.example.com/example#myanchor1),或修改现有代码以接受您传递给它的内容你的新代码。

Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.

Edit after comment

For example, you might have this code in your HTML:

<a href="example#myanchor1" class="myHash">example1</a>
<a href="example#myanchor2" class="myHash">example2</a>
<a href="example#myanchor3" class="myHash">example3</a>

Then, you could add the following code to bind and respond to the links:

<script type="text/javascript">
    $('a.myHash').click(function(e) {
        e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
        var linkHref = $(this).attr('href'); // Grab the URL from the link
        if (linkHref.indexOf("#") != -1) { // Check that there's a # character
            var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
            myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
            alert(hash); // Just for fun.
        }
    });
</script>

Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.

Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.

甜中书 2024-09-03 10:29:53

这与我所做的类似(其中“anc”不用于其他任何用途):

<a href="/example?anc=myanchor2"></a>

并且 onload:

window.onload = function() {
    var hash = document.location.hash.substring(1);
    if (hash.length == 0) {
        var anc = getURLParameter("anc");
        if (anc != null) {
            hash = document.location.hash = anc;
        }
    }
}

getURLParameter 函数来自 此处

Here's something like what I did (where "anc" isn't used for anything else):

<a href="/example?anc=myanchor2"></a>

And onload:

window.onload = function() {
    var hash = document.location.hash.substring(1);
    if (hash.length == 0) {
        var anc = getURLParameter("anc");
        if (anc != null) {
            hash = document.location.hash = anc;
        }
    }
}

The getURLParameter function is from here

澉约 2024-09-03 10:29:53

试试这个对我有帮助

click me

在你的锚标记中而不是

点击我

Try this its help for me

<a onclick="location.href='link.html'">click me</a>

In your anchor tag instead of

<a href="link.html">click me </a>

飞烟轻若梦 2024-09-03 10:29:53

如果您需要使用相同锚点重新加载页面并期望浏览器返回到该锚点,则不会。它将返回到用户的上一个滚动位置

设置随机锚点,覆盖它然后重新加载似乎可以修复它。不完全确定原因。

var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();

If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.

Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.

var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
独享拥抱 2024-09-03 10:29:53

正如另一个答案中所建议的,监视哈希也是一种选择。我最终像这样解决了这个问题,因此只需要很少的代码更改。如果我问了最初的问题,我相信我会很高兴看到这个选项得到充分解释。

额外的好处是它允许针对任何一种情况(哈希更改或页面加载)添加额外的代码。它还允许您使用自定义哈希手动调用哈希更改代码。我使用 jQuery 是因为它使哈希更改检测变得轻而易举。

开始吧!

将检测到哈希时触发的所有代码移至单独的独立函数中:

function openHash(hash) {

  // hashy code goes here

  return false; // optional: prevents triggering href for onclick calls
}

然后检测这两种情况的哈希,如下所示:

// page load
$(function () {
  if(typeof location.hash != typeof undefined) {
    // here you can add additional code to trigger only on page load
    openHash(location.hash);
  }
});

// hash change
$(window).on('hashchange', function() {
  // here you can add additional code to trigger only on hash change
  openHash(location.hash);
});

并且您现在也可以像这样手动调用代码

<a href="#" onclick="openHash('super-custom-hash')">Magic</a>

希望这对任何人都有帮助!

As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.

The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.

Here goes!

Move all the code that fires when a hash is detected into a separate independent function:

function openHash(hash) {

  // hashy code goes here

  return false; // optional: prevents triggering href for onclick calls
}

Then detect your hash for both scenarios like so:

// page load
$(function () {
  if(typeof location.hash != typeof undefined) {
    // here you can add additional code to trigger only on page load
    openHash(location.hash);
  }
});

// hash change
$(window).on('hashchange', function() {
  // here you can add additional code to trigger only on hash change
  openHash(location.hash);
});

And you can also call the code manually now like

<a href="#" onclick="openHash('super-custom-hash')">Magic</a>

Hope this helps anyone!

孤芳又自赏 2024-09-03 10:29:53

通过添加简单的问号来尝试此操作:

通过刷新转到 Anchor2

Try this by adding simple question mark:

<a href="?#anchor2">Going to Anchor2 with Refresh</a>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文