Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/91.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript If语句问题_Javascript_Html - Fatal编程技术网

JavaScript If语句问题

JavaScript If语句问题,javascript,html,Javascript,Html,我是新来的,这是我要问的第一个问题 我是一名编程和编码的初学者,我正在尝试建立一个基本系统,通过输入学生的学校编号来查看学生的分数。 这是我的密码:- <html> <body> <head> <title>Test</title> </head> <input type="text" id="txtjob"> <button onclick="getnatega()">OK</button&

我是新来的,这是我要问的第一个问题

我是一名编程和编码的初学者,我正在尝试建立一个基本系统,通过输入学生的学校编号来查看学生的分数。 这是我的密码:-

<html>
<body>
<head>
<title>Test</title>
</head>

<input type="text" id="txtjob">
<button onclick="getnatega()">OK</button>


<script>
function getnatega() {
if (txtjob == 2386) {
window.location.href = "www.ex.com";
}
}
</script>
</body>
</html>

试验
好啊
函数getnatega(){
if(txtjob==2386){
window.location.href=“www.ex.com”;
}
}
但每当我点击“确定”按钮时,什么都不会发生。
我会感谢任何帮助我的人。

什么都不会发生,因为
txtjob
没有定义。如果要获取输入的值,它位于
document.getElementById(“txtjob”).value

中,您需要访问元素本身并从中取出值。结果是一个字符串

函数getnatega(){ if(document.getElementById('txtjob')。值=='2386'){ window.location.href=“www.ex.com”; } }


好的
您需要使用
文档
API来获取对JavaScript中元素的引用。可以将该元素指定给变量,这样就不必每次都调用该方法

var txtJob = document.getElementById('txtjob');
function getnatega() {
  if (txtJob.value == '2386') {
    window.location.href = "www.ex.com";
  }
}

在某些浏览器中,引擎会使用元素的ID定义一个全局变量,这是一个怪癖。如果(window.txtjob.value=='2386')正常运行,您可能可以不使用
if(window.txtjob.value=='2386')
,但即使它有效,我也不建议使用它,因为它不是一种标准化的行为,并且所有浏览器可能不会做相同的事情。但是,它们都有
文档
API,您可以使用它来正确地获取对如上所示元素的引用。

这是正确的代码

<html>

<head>
<title>Test</title>
<script type="text/javascript">
function getnatega() 
{
  var a=document.getElementById('txtjob').value;

  if ( a == 2386) 
  {
    window.location.href = "www.ex.com";
  }
}
</script>
</head>
<body>

<input type="text" id="txtjob">
<button onclick="getnatega()">OK</button>


</body>
</html>

试验
函数getnatega()
{
var a=document.getElementById('txtjob').value;
如果(a==2386)
{
window.location.href=“www.ex.com”;
}
}
好啊

在我看来很合理?因为结果是字符串,而您使用的是非引号的
2386
它不应该,如果要使用
==
,我错过了,您没有。。。删除评论并删除VoteTanks,我感谢您帮助我的努力。这已经足够了。Asker应该做一些工作,我更喜欢解释,而不是给代码进行复制和粘贴。