2017-08-27 136 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">

相關問題