javascript:从学生ID输出名称的最简单方法

时间:2017-11-25 16:15:56

标签: javascript html numbers lookup

我的JS CODE

<script language="Javascript">
var data = {
   7: "Jack Black",
   8: "John Smith"
};

var id = document.getElementById("id"),
  emp = document.getElementById("name");
id.addEventListener("keyup", function() {
  emp.value = data[this.value] || "No name with this ID Number";
});
</script>

在HTML中我有

<input type="number" id="id" />
<input type="text" disabled="disabled" id="name" />

那么我做错了什么,当我输入7时怎么样,Jack Black没有出现在文本框内?

非常感谢

2 个答案:

答案 0 :(得分:2)

问题必须在html文件中脚本标记的位置,你需要在使用javascript使用id获取ID之前定义标识为document.getElementById("id")的html元素,这似乎成为代码的唯一问题。

首先播放脚本内容,然后播放html,导致错误

&#13;
&#13;
<script language="Javascript">
  var data = {
    7: "Jack Black",
    8: "John Smith"
  };

  var id = document.getElementById("id"),
    emp = document.getElementById("name");
  id.addEventListener("keyup", function() {
    emp.value = data[this.value] || "No name with this ID Number";
  });
</script>

<input type="number" id="id" />
<input type="text" disabled="disabled" id="name" />
&#13;
&#13;
&#13;

如果我们颠倒顺序并首先定义html,那么脚本就没有错误!

&#13;
&#13;
<input type="number" id="id" />
<input type="text" disabled="disabled" id="name" />

<script language="Javascript">
var data = {
   7: "Jack Black",
   8: "John Smith"
};

var id = document.getElementById("id"),
  emp = document.getElementById("name");
id.addEventListener("keyup", function() {
  emp.value = data[this.value] || "No name with this ID Number";
});
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您的代码有效!但是,如果您想使用数字输入的箭头,请使用change-event。

// maybe it would be better to make an array
var data = {
   7: "Jack Black",
   8: "John Smith"
};

var id = document.getElementById("id"),
  emp = document.getElementById("name");

function changeValue() {
  emp.value = data[this.value] || "No name with this ID Number";
}

// event listener
if (id.addEventListener) { // new browsers
	id.addEventListener("keyup", changeValue, false);
	id.addEventListener("change", changeValue, false);
} else if (id.attachEvent) { // IE <9, Opera <6
	id.attachEvent("onkeyup", fchangeValue);
  id.attachEvent("onchange", fchangeValue);
} else { // old browsers
	id.onkeyup = changeValue;
  id.onchange = changeValue;
}
<input type="number" id="id" />
<input type="text" disabled="disabled" id="name" />