簡體   English   中英

未觸發 JavaScript 事件

[英]JavaScript event not being fired

單擊#theButton ,應觸發警報。 為什么使用以下方法沒有觸發任何事件?

            var theButton = document.getElementById("theButton");
       
            theButton.onclick = function(){alert("Clicked!");}
            theButton.onclick = clickAlert;
            theButton.onclick(alert("Clicked!"));
    
            function clickAlert(){
                alert("Clicked!");
            }
        </script>
    </head>
    <body>
        <input type="button" id="theButton">
    </body>
</html>

你有三個問題

  1. 您在第 7 行拼錯了function 。(順便說一下,這會產生運行時錯誤)
  2. 您嘗試在節點 #theButton 在 DOM 中可用之前訪問它。 聽聽 Pekka 的建議
  3. 您覆蓋了第 8 行的onclick屬性 - 不確定您是故意這樣做還是什么

因為當您運行腳本時theButton還不存在?

將它包裝到主體的onload事件或 jQuery 的ready()

嘗試將其包裝在 document.Ready() 函數中。

我喜歡jQuery.ready()答案,但我相信您也可以將<script>塊移動到某個點,就像在頁面末尾一樣取消按鈕。

如果您將 onclick 放在輸入標簽中(並且拼寫正確),它會起作用:

<html>
     <head>
      <script type="text/javascript" language="javascript">



       function clickAlert(){
        alert("Clicked!");       

       }

      </script>
     </head>
     <body>
      <input type="button" id="theButton" NAME="theButton" onclick="clickAlert()">
     </body>
    </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM