2017-08-27 140 views
-1

我试图在前一个输入达到其最大长度值时重点关注下一个输入。但它不适用于我的代码。JavaScript代码不在本地工作,但在jsfiddle中工作

<html> 
    <head> 
    <script> 
     var a = document.getElementById("num1"), 
      b = document.getElementById("num2"), 
      c = document.getElementById("num3"); 

     a.onkeyup = function() { 
      if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
       b.focus(); 
      } 
     } 
     b.onkeyup = function() { 
      if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
       c.focus(); 
      } 
     } 
    </script> 
    </head> 

<body> 
    <input type="text" id="num1" maxlength="3"> 
    <input type="text" id="num2" maxlength="2"> 
    <input type="text" id="num3" maxlength="6"> 
</body> 
</html> 
+0

脚本应该体内后加载,或者至少你的逻辑应该一个DOM准备处理程序中被包装。由于脚本在头部,因为主体已完全加载,因此执行该脚本:在这种情况下,元素在运行时不可用。 – Terry

+0

在发布之前请[搜索](/ search?q =%5Bjs%5D + doesn%27t + work +但+ +在+小提琴中工作)。更多关于搜索[这里](/帮助/搜索)。 –

回答

0

以下是编辑后的代码,其中包含以下编辑:

  • 变量定义结尾的分号不正确。
  • 将脚本移到代码的末尾,而不是开头。这将导致变量的空指向,因为在定义时元素不在那里。
<html> 
<head> 
    <!--script moved down--> 
</head> 
<body> 
    <input type="text" id="num1" maxlength="3"> 
    <input type="text" id="num2" maxlength="2"> 
    <input type="text" id="num3" maxlength="6"> 

    <script> 
     //semicolon correction here 
     var a = document.getElementById("num1"); 
     var b = document.getElementById("num2"); 
     var c = document.getElementById("num3"); 

     a.onkeyup = function() { 
      if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
       b.focus(); 
      } 
     }; 
     b.onkeyup = function() { 
      if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
       c.focus(); 
      } 
     }; 
    </script> 
</body> 
</html> 
0

有问题,在确定这些3个变量,而不是逗号,你应该添加分号也可以从bc添加逗号,但删除var

var a = document.getElementById("num1"); 
 
var b = document.getElementById("num2"); 
 
var c = document.getElementById("num3"); 
 

 
/* 
 
var a = document.getElementById("num1"), 
 
b = document.getElementById("num2"), 
 
c = document.getElementById("num3"); 
 
*/ 
 

 

 
a.onkeyup = function() { 
 
    if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
 
    b.focus(); 
 
    } 
 
} 
 
b.onkeyup = function() { 
 
    if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
 
    c.focus(); 
 
    } 
 
}
<input type="text" id="num1" maxlength="3"> 
 
<input type="text" id="num2" maxlength="2"> 
 
<input type="text" id="num3" maxlength="6">

相关问题