简体   繁体   English

为什么我的函数提示(Javascript)不起作用?

[英]Why does my function prompt(Javascript) doesn't work?

I dont understand why my function only works in the "live demonstration" of 'Brackets', but not when I try to open it with my index.html file... 我不明白为什么我的函数只能在“ Brackets”的“实时演示”中起作用,而当我尝试使用index.html文件打开它时却不起作用...

Thats my function for a password protected area: 这就是我的密码保护区域功能:

function passWord() {
 var testV = 1;
 var pass1 = prompt('Please Enter Your Password',' ');
  while (testV < 3) {
   if (!pass1) 
   history.go(0);
   if (pass1.toLowerCase() == "letmein") {
   alert('You Got it Right!');
   window.open('/html/ok.html',"_self");
   break;
   } 
  testV+=1;
  var pass1 = 
  prompt('Access Denied - Password Incorrect, Please Try     Again.','Password');
 }
 if (pass1.toLowerCase()!="password" & testV ==3) 
 history.go(0);
 return " ";
}  

Please help me, Thanks all :D 请帮助我,谢谢大家:D

That's a nice function.. Anyways, are you actually calling the function inside your index.html ? 那是一个很好的函数。无论如何,您实际上是在index.html调用该函数吗?

<html>
<head>
   <script>
      function passWord() {
         //... (place your code here)
      }
   </script>
</head>
<body onload="passWord()"></body> <!--here you actually call the function-->
</html>

This is just one option, which is kinda frowned upon to use event callers inside html. 这只是一个选项,在html内使用事件调用程序时,对此有些皱眉。 You can also add the function call in your script tag: 您还可以在脚本标签中添加函数调用:

<script>
   function passWord() {
       //... (place your code here)
   }
   passWord(); //now the function actually gets executed
</script>

Because you're refreshing the page with history.go(0); 因为您正在使用history.go(0);刷新页面history.go(0); which resets the value of testV . 重置testV的值。

I added some console logs so you can see what's going on: 我添加了一些控制台日志,以便您可以查看发生了什么:

function passWord() {
  var testV = 1;
  var pass1 = prompt('Please Enter Your Password');
  while (testV < 3) {
    if (pass1.toLowerCase() == "letmein") {
      alert('You Got it Right!');
      window.open('/html/ok.html', "_self");
      break;
    }
    testV++;
    var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.');
    console.log(testV);
  }
  if (pass1.toLowerCase() != "password" & testV == 3)
  {
    console.log("Refresh");
    history.go(0);
  }
  return " ";
}

passWord();

Fiddle: https://jsfiddle.net/s2ejwk9p/ 小提琴: https//jsfiddle.net/s2ejwk9p/

Take out the history.go(0); 取出history.go(0); and you'll be ok. 一切都会好起来的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM