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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2573979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:59:15  来源:igfitidea点击:

Force page reload with html anchors (#) - HTML & JS

javascriptjqueryhtmlanchor

提问by Yuval Karmi

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

假设我在一个名为/example#myanchor1where myanchoris an anchor 的页面上。我想链接到/example#myanchor2,但在这样做时强制页面重新加载。

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.

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

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

我该怎么做?JS没问题。

采纳答案by falstro

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

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

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

where in place of $randominsert 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.

其中$random插入一个随机数(假设“虚拟”不被解释为服务器端)。我确信有一种方法可以在设置锚点后重新加载页面,但它可能比简单地对设置的锚点做出反应并在那时做你需要的事情更困难。

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

再说一次,如果您以这种方式重新加载页面,您可以myanchor2改为将其作为查询参数,并在服务器端呈现您的东西。

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.

不过,我仍然建议只监控哈希值。

回答by Qwerty

Simple like that

就这么简单

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

an example

一个例子

回答by Stilltorik

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

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

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

Basically, the setTimeoutdelays the reload. As there is no return falsein the onclick, the hrefis performed. The url is then changed by the hrefand only after that is the page reloaded.

基本上,setTimeout延迟重新加载。由于return falseonclick 中没有,所以href执行。然后 url 被更改href,只有在此之后页面才会重新加载。

No need for jQuery, and it is trivial.

不需要jQuery,而且很简单。

回答by Matti Virkkunen

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.

如果您要一直重新加载页面,那么使用客户端 JS 有什么意义?即使页面没有重新加载,监控哈希值的变化也可能是一个更好的主意。

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

这个页面有一个哈希监视器库和一个 jQuery 插件。

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

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

回答by Blair McMillan

Another option that hasn't been mentioned yet is to bind event listeners (using jQueryfor 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.

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

Edit after comment

评论后编辑

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

例如,您的 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 selectorto select the links I want to 'monitor', but you can use whatever selectoryou want.

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

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.

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

回答by Dário

My favorite solution, inspired by another answeris:

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

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

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

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

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.

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

回答by bourne2program

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

这就像我所做的一样(其中“anc”不用于其他任何东西):

<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

getURLParameter 函数来自这里

回答by prashant kute

Try this its help for me

试试这个对我有帮助

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

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

In your anchor tag instead of

在你的锚标签而不是

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

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

回答by eleven59

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.

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

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!

希望这可以帮助任何人!

回答by Abid Ali

Try this by adding simple question mark:

通过添加简单的问号来试试这个:

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

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