把JS写成div

时间:2017-04-17 16:52:11

标签: javascript html css

我在我的网站中设置了一个开关案例,如果我使用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>

2 个答案:

答案 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)

  1. 如果你使用getElementById,你需要一个id,而不仅仅是一个名字;我添加了一个带有另一个输出ID的范围
  2. 表单字段的.value不是.innerHTML - innerHTML用于标记,例如span和p
  3. type = button - 如果在表单
  4. 您无法在容器代码上拆分表单
  5. 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>