检查条件后转到给定的网址

Go to given url after checking condition

本文关键字:条件 检查      更新时间:2023-09-26

Arter 单击我需要在javaScript中运行chkMethode(),然后我决定是否转到url

当我单击"Go"时,它不会直接运行chkMethode()转到给定的链接。 怎么办?

     <a href="http://www.google.com" onclick="chkMethode()"> Go </a>

这是因为 JavaScript 需要阻止锚点执行其通常的事件,并且它使用 preventDefault 来执行此操作。在这里,作为最佳实践,我已经将您的 JS 与 HTML 分开并使用了一个id

.HTML

<a id="go" href="http://www.google.com">Go</a>

.JS

var go = document.getElementById('go');
go.onclick = chkMethode;
function chkMethode(e) {
  e.preventDefault();
  if (check) {
    window.location.href = this.getAttribute('href');
  }
}
function chkMethode(event)
{
  if (<<certain condition>>)
  {
    event.preventDefault();
    return false;
  }
}
<a href="http://www.google.com" onclick="return chkMethode(event)"> Go </a>
<a onclick="event.preventDefault();chkMethode();" href="http://www.google.com" > Go </a>
Function chkMethode () {
    Var valuetochck = // value to be checked
    If(valuetochck == "")
    {
        Window.location.href="url1";
    }
    Else
    {
        Window.location.href="url2";
    }
}