我收到错误 - 函数sayHi()没有定义,我不明白

时间:2016-08-11 16:50:52

标签: javascript html

从HTML正文调用时,JavaScript函数没有响应。 我一直收到函数sayHi()未定义的错误。

    

<head>
  <meta charset="UTF-8">
  <title>innerHTML.html</title>

  <script type = "text/javasctipt">
      // javasctipt
      function sayHi(){
          txtName = document.getElementById("txtName");
          divOutput = document.getElementById("divOutput");

          var name = txtName.value;

          divOutput.innerHTML = "<em>" + name + "</em>";
          divOutput.innerHTML += " is very nice name.";
      }
  </script>

</head>

<body>
    <h1>Inner HTML Demo</h1>

    <form action = "">
        <fieldset>
            <label>Please type your name</label>
            <input type = "text"
                   id = "txtname" />
            <button type = "button"
                    onclick = "sayHi()" >
                Click Me
            </button>   
        </fieldset>

    </form>

    <div id = "divOutput">
        Watch this space
    </div>


</body>
</html>

3 个答案:

答案 0 :(得分:2)

您的<script>标记错误:

<script type = "text/javasctipt">

你真的不需要“类型”或“语言”属性,所以只需使用

<script>

如果您觉得有必要使用“type”,请使用正确的类型:

<script type="text/javascript">

如果“type”属性不是浏览器识别的内容,则<script>内容将被完全无声地忽略。

答案 1 :(得分:1)

您元素的ID为'txtname',但您希望得到'txtName'

&#13;
&#13;
<head>
  <meta charset="UTF-8">
  <title>innerHTML.html</title>
<script>
  
 
      function sayHi(){
         txtName = document.getElementById("txtname");
         divOutput = document.getElementById("divOutput");

         var name = txtName.value;

         divOutput.innerHTML = "<em>" + name + "</em>";
         divOutput.innerHTML += " is very nice name.";
      }
 
  </script>
</head>

<body>
    <h1>Inner HTML Demo</h1>

    <form action = "">
        <fieldset>
            <label>Please type your name</label>
            <input type = "text"
                   id = "txtname" />
            <button type = "button"
                    onclick='sayHi()'>
                Click Me
            </button>   
        </fieldset>

    </form>

    <div id = "divOutput">
        Watch this space
    </div>




</body>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

脚本标记的type属性中存在拼写错误。请将其从text / javasctipt更改为text / javascript。它会起作用。