簡體   English   中英

將javascript代碼放在 <head> 標簽

[英]put the javascript code between the <head> tags

我想使用匿名函數將腳本放在<head>標記之間,並添加onclick事件以更改標記p的內容,但是單擊后什么也沒有發生。 我的腳本有什么問題嗎,請幫幫我。 謝謝

<!DOCTYPE html> <html lang="en">    
<head>      
  <title>web</title>
  <script>
        window.onload=function(){
            function rubah1(){
                document.getElementById("text1").innerHTML="SUDAH BERUBAH TEXT 1";
            }
        }       
  </script>     
</head>     
<body>      
  <p id="text1">Teks 1 Sebelum Di Rubah</p>
  <button type="button" onclick="rubah1();">Rubah Text 1</button>   
</body> 
</html>

請下次更好地格式化代碼。 您無需等待文檔加載就可以定義函數。 您只需在頭部定義,然后該按鈕將起作用。 工作代碼段:

  <!DOCTYPE html> <html lang="en"> <head> <title>web</title> <script> function rubah1() { document.getElementById("text1").innerHTML = "SUDAH BERUBAH TEXT 1"; } </script> </head> <body> <p id="text1">Teks 1 Sebelum Di Rubah</p> <button type="button" onclick="rubah1();">Rubah Text 1</button> </body> </html> 

方法的問題是,您在onload函數的內部范圍內定義了該函數,因此該按鈕對按鈕不可見。

函數rubah1在onload中定義。 因此,它的范圍不是全球性的。 函數rubah1的生命僅在onload內。 超出onload范圍的代碼無法調用它,因為該代碼不知道存在名為rubah1的函數。 您可以刪除onload,因為它似乎並沒有增加任何價值。
您可以通過參考以下內容來幫助自己:它將清除您的概念: w3schools Javascript范圍教程

更新的代碼:

<!DOCTYPE html> <html lang="en">    
<head>      
  <title>web</title>
  <script>
    window.onload=function(){
        function rubah1(){
            document.getElementById("text1").innerHTML="SUDAH BERUBAH TEXT 1";
        }
    }       
</script>     
</head>     
<body>      
  <p id="text1">Teks 1 Sebelum Di Rubah</p>
  <button type="button" onclick="rubah1();">Rubah Text 1</button>   
</body> 

暫無
暫無

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

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