简体   繁体   中英

put the javascript code between the <head> tags

I want to put the script between the <head> tags using the anonymous function and I add the onclick event to change the contents of the tag p but after I click nothing happens. Is there anything wrong from my script please help me. thank you

<!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>

Please format your code better next time. You don't need to wait for the document to load to define a function. You can just define in in the head and then the button will work. Working code snippet:

  <!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> 

The problem with your approach is that you define the function in the inner scope of the onload function, and thus is not visible to the button.

The function rubah1 is defined within onload. Hence, its scope is not global. function rubah1's life is only within onload. Code that is out of scope of onload cannot call it because that code doesn't know that a function named rubah1 exists. You can remove onload as it doesn't seem to add any value to it.
You can help yourself by referring this which will clear your concepts: w3schools Javascript scope tutorial .

Updated Code:

<!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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM