javascript代码不在本地工作,但在jsfiddle中工作

时间:2017-08-27 07:52:06

标签: javascript html

我试图在前一个输入达到其最大长度值时聚焦下一个输入。但它不适用于我的代码。

  <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>

2 个答案:

答案 0 :(得分:1)

以下是编辑后的代码:

  • 变量定义末尾的分号不正确。
  • 将脚本移动到代码的末尾,而不是开头。它会导致变量的空值,因为在定义时元素不存在。
<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>

答案 1 :(得分:0)

定义这3个变量时出现问题,而不是逗号,你应该添加分号OR,你可以添加逗号,但从varb删除c

&#13;
&#13;
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();
  }
}
&#13;
<input type="text" id="num1" maxlength="3">
<input type="text" id="num2" maxlength="2">
<input type="text" id="num3" maxlength="6">
&#13;
&#13;
&#13;