我在我的网站中设置了一个开关案例,如果我使用document.write(),它会起作用,但这样做会在新屏幕中打开结果,我希望它将结果打印到div 。我没有JS的经验;我正在尝试document.getElementById(),但我不认为我完全掌握了它的概念:
<form id="form1">
<p>Enter 7 digit CPN : <input name="cpn" type="text" size="20"> (CAPITALIZE all letters)</form>
<button onclick="outputname()"> Submit</button></p>
<script>
function outputname(){
var x,name,a,b,answer,y;
x=document.getElementById("form1");
y=x.elements["cpn"].value;
switch(y){
case "LIG007":
text = "LIG007: Located in the 737 Avionics Cart Drawer 1. Keyword LIGHT";
break;
case "4080703":
text = "4080703: Located in the 737 Avionics Cart Drawer 1. Keyword LAMP";
break;
case "4089797":
text = "4089797: Located in the 737 Avionics Cart Drawer 1. Keywork IDENTIFIER";
break;
default:
text = "CPN NOT FOUND, PLEASE MAKE SURE IT WAS TYPED CORRECTLY.";
}
document.getElementById('cpn')innerHTML;
}
</script>
答案 0 :(得分:2)
你几乎得到了它。尝试;
document.getElementById('cpn').innerHTML = text;
作为旁注,请在switch语句的外部(上方)定义var text = ""
。
您可以在https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
找到有关innerHTML的更多信息<强> 修改 强>
假设您尝试从输入字段中获取值并使用它来确定要在div中放置的文本,则需要更改中的 ID .innerHTML 以匹配div的ID。
答案 1 :(得分:0)
function outputname() {
var x, name, a, b, answer, y;
x = document.getElementById("form1");
y = x.elements["cpn"].value;
switch (y) {
case "LIG007":
text = "LIG007: Located in the 737 Avionics Cart Drawer 1. Keyword LIGHT";
break;
case "4080703":
text = "4080703: Located in the 737 Avionics Cart Drawer 1. Keyword LAMP";
break;
case "4089797":
text = "4089797: Located in the 737 Avionics Cart Drawer 1. Keywork IDENTIFIER";
break;
default:
text = "CPN NOT FOUND, PLEASE MAKE SURE IT WAS TYPED CORRECTLY.";
}
document.getElementById('cpnOut').innerHTML=text;
}
<form id="form1">
<p>Enter 7 digit CPN : <input id="cpn" name="cpn" type="text" size="20"> (CAPITALIZE all letters)
<button type="button" onclick="outputname()"> Submit</button></p>
</form>
<span id="cpnOut"></span>