如何使html< a>元素具有a href但默认为onclick?

olhwl3o2  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(248)

我有一个 <a> 在我的html页面内。我用javascript编写了一个自定义重定向程序,因此当您单击按钮时,它会运行一个javascript函数,在重定向之前执行重要任务。例如:

function go(page) {
  alert("You are being redirected!")
  // Important things here, such as saving
  open(page, target="_self")
}
a {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
Link: <a onclick="go('/nextPage')">Click me to go to the next page!</a>

在上面的示例中,链接运行脚本以执行函数,然后打开url。但是,如果右键单击该链接,则与其他链接一样,没有“在新选项卡中打开”选项,因为它没有 href . 如果有 href ,它转到下一个选项卡,而不运行js。有没有可能使它有一个href,这样右键单击就可以工作,但仍然运行js?因此,基本上,它将授予 onclick 事件,而不是运行 href 除非单击鼠标右键。
我试着取下那根绳子 onclick 和使用 href="javascript:go('/nextPage);" 相反,但右键单击会使其转到 about:blank#blocked 镀铬的。

w1e3prcc

w1e3prcc1#

对于html,我很抱歉,我必须尝试不同的编辑器来检查结果。
试试这个

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
  <script>

      function go(page) {
      alert("You are being redirected!")
        // Important things here, such as saving
       return false;  // equivalent to preventDefault
      }

  </script>
<body>
   <a href='http://www.example.com' onclick='return go()'>Click me to go to the next page!</a>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
  <script>

   function go(event) {
     if( !confirm(`Redirect to ${event.target.href} ?`) ) 
         event.preventDefault();
      }

  </script>
<body>
   <a href='/example' onclick="go(event)"> Click me to go to the next page! </a>
</body>
</html>
9nvpjoqh

9nvpjoqh2#

不要使用 onclick . 相反,添加一个 click 阻止默认操作的所有锚标记上的事件侦听器(通过 e.preventDefault() )而是打电话给 go 功能。

function go(page) {
  alert("You are being redirected!")
  // Important things here, such as saving
  open(page, target = "_self")
}

document.querySelectorAll('a').forEach((f) => {
  f.addEventListener('click', function(e) {
    e.preventDefault();
    go(this.getAttribute('href'));
  })
})
a {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
Link: <a href="https://stacksnippets.net">Click me to go to the next page!</a>

相关问题