使用html锚点强制页面重新载入(#) - HTML& JS [英] Force page reload with html anchors (#) - HTML & JS

查看:153
本文介绍了使用html锚点强制页面重新载入(#) - HTML& JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在一个名为 / example#myanchor1 的页面上,其中 myanchor 是页面中的一个锚点。
我想链接到 / example#myanchor2 ,但强制页面重新加载。



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



我这么做? JS是确定的。

解决方案

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

 < a href = > 虚设= $随机#myanchor2?;< / A> 

代替 $ random 插入a随机数(假设虚拟不解释服务器端)。我确信有一种方法可以在设置锚点后重新加载页面,但这可能更困难,然后只需对设置的锚点进行响应,然后执行您当前所需的内容即可。



然后,如果您以这种方式重新加载页面,则可以将 myanchor2 作为查询参数,并渲染您的东西服务器端。



编辑

请注意,上面的链接会在所有情况下重新加载,如果您只需要重新加载在这个页面中,你需要让虚拟变量更具可预测性,就像这样


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

我仍然建议只监视哈希。


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.

解决方案

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.

这篇关于使用html锚点强制页面重新载入(#) - HTML&amp; JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆