在网站上有一个代码,与alert一起工作,但在满足if条件时不链接到另一个网站

Having a code on website that works with alert but doesn't link to another website when the if condition is met

本文关键字:网站 条件 if 链接 满足 另一个 工作 有一个 代码 一起 alert      更新时间:2023-09-26

我的HTML/JAVASCRIPT文档有问题,我复制了下面的代码。

我已经创建了一个输入文本框和一个运行函数check()的按钮。通过使用警报,代码执行得很好,但是当我将警报替换为一个链接时,该链接将在满足条件时将用户引导到一个网页。

在我的例子中,条件是40。

我有一个外部样式表链接到文档和附加的外部Javascript脚本。

谢谢…

编辑 -这可能更容易,我已经做了一个简单的文件,所有的代码,我想在

下面执行
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function check (){
    var codeEntered = document.getElementById("promocode").value;
      if (codeEntered==40)
  {
 //alert ("work")
 window.location.assign = "http://www.w3schools.com";
  }
  else if (codeEntered == "")
  {
  alert ("Please Enter a Promotional Code.")  
  }
  else
  {
  alert ("Promotional code incorrect")
  }
}
</script>
<body>
<form id="form3" name="form3" method="post" action="">
      <label for="promocode">Promotional Code:</label>
      <input type="text" name="promocode" id="promocode" />
    </form>
    <p></p>
<p>&nbsp;</p>
<form id="form1" name="form1" method="post" action="">
  <input type="submit" name="Submit" id="Submit" value="Submit Code" onclick="check()" />
</form>
</body>
</html>

提交按钮所在的form,在页面有机会重定向之前被发布。

考虑到您没有发布任何数据,您实际上并不需要这两个表单。如果你想用一些东西来包围元素,以增加风格,使用div代替。

注意window.location.assign也被改成了window.location

<script type="text/javascript">
function check(){
  var codeEntered = document.getElementById("promocode").value;
  if (codeEntered==40)
  {
    window.location = "http://www.w3schools.com";
  }
  else if(codeEntered == "")
  {
    alert("Please Enter a Promotional Code.")  
  }
  else
  {
    alert("Promotional code incorrect")
  }
}
</script>
<body>
      <label for="promocode">Promotional Code:</label>
      <input type="text" name="promocode" id="promocode" />
  <p>&nbsp;</p>
  <button type="button" value="Submit Code" onclick="check()" >Submit Code</button>
</body>
</html>

您正在尝试设置窗口。将Location属性设置为HTML锚元素,而不是将其设置为要将页面发送到的位置。

试试这个:

window.location = "http://www.w3schools.com";

试试这个

window.location.assign("http://www.w3schools.com")

编辑:

window.open('http://www.w3schools.com','_self',false)

try this:

location.href = " http://www.w3schools.com ",

赋值可能比调用函数更快。

访问http://jsperf.com/location-href-vs-location-assign获取更多详细信息。

你还需要在JS函数中包含"return false;":

并像这样调用:

<input type="submit" name="Submit" id="Submit" value="Submit Code" onclick="**return** check();" />

和javascript函数如下:

function check() {
        window.location.href = "http://www.w3schools.com" ;
        return false;
    }