重定向锚从URL指定Onload

Redirect Anchor from URL to specify Onload

本文关键字:指定 Onload URL 重定向      更新时间:2023-09-26

在我们的网站上,我们有一个页面,我们有5个图像是按钮。当您单击每个按钮时,使用onclick功能将显示更详细的信息。

我们想做的是从URL www.example.com#program中提取锚信息,然后使用该锚来指定我们想要加载的onload。

所以理论上,www.example.com#program会执行这个:

<img src="program.png" width="159" height="115"
   onload=
    "ShowHide('ACE', 'hidden');
     ShowHide('program', 'visible');
     ShowHide('ACE2', 'hidden');
     ShowHide('ACE3', 'hidden');
     ShowHide('ACE4', 'hidden'); "/>

www.example.com#ACE将执行以下命令:

<img src="ACE.png" width="159" height="115"
   onload=
    "ShowHide('ACE', 'visible');
     ShowHide('program', 'hidden');
     ShowHide('ACE2', 'hidden');
     ShowHide('ACE3', 'hidden');
     ShowHide('ACE4', 'hidden'); "/>

任何帮助都将非常感激!

如果您监视散列的更改,则可以更动态地执行此操作:

var sections = ['ACE', 'program', 'ACE2', 'ACE3', 'ACE4'];
window.onhashchange = function(evt) {
   var hash = location.hash.substr(1);
   // iterate sections and make section at location.hash visible
   sections.forEach(function(section) {
      var visibility = 'hidden';
      if(section === hash) {
         visibility = 'visible';
      }
      ShowHide(section, visibility);
   });
};

您可以在这里查看此演示:https://jsfiddle.net/a41j5ed7/,打开控制台,查看哪些项是可见的,哪些是隐藏的。

由于已经为每个图像按钮设置了onclick设置,因此需要在用户单击按钮时更新散列。您没有发布处理图像按钮单击的代码,但它将类似于:

imageButton.onclick = function() {
   // whatever you are currently doing when the user clicks the image button
   location.hash = 'ACE'; // or whichever button they clicked
}