简体   繁体   中英

how to make an event happen when click a button on HTML by using javascript

I am trying to make HTML print out "Germany" when you click the button. But it is not working correctly. Is there something wrong in my code?

HTML

<input type="button" value="click!" onclick="shuffle();"/>
<div id="output"></div>

Javascript

(function(){
    window.onload = function(){
        alert("welcome to my trip record");
    }
})();

var shuffle = function(){
    var target = document.getElementById("output");
    target.innerHTML = "Germany";
}

Remove the ; from your onclick

<input type="button" value="click!" onclick="shuffle()"/>

Try to use addEventListener for make event on button click

document.getElementById("myBtn").addEventListener("click", function(){
    var target = document.getElementById("output");
    target.innerHTML = "Germany";
});

here is the working jsfiddle: https://jsfiddle.net/jxjpzvvz/

<button id='btn_click' type="button">Click me!</button>
<div id="output"></div>

use button element for buttons, not input type button. we are not in the time of html 4.0 ;)

(function(){
    window.onload = function(){
        alert("welcome to my trip record");
    }
})();

var shuffle = function(event){
    var target = document.getElementById("output");
    target.innerHTML = "Germany";
}

document.getElementById('btn_click').addEventListener('click', shuffle);

i'm fan of no js in the html tags directly, so i add a listener to the element

You made two mistakes First mistake <input /> this is nothing. Second most common "function ();", the ";" Is wrong

Your corrected code

 (function(){ window.onload = function(){ alert("welcome to my trip record"); } })(); var shuffle = function(){ var target = document.getElementById("output"); target.innerHTML = "Germany"; } 
 <input type="button" value="click!" onclick="shuffle()"/> <div id="output"></div> 

I like to use DOM EventListener

 window.onload = function(){ alert("welcome to my trip record"); } document.getElementById("myBtn").addEventListener("click", function_t); function function_t(){ var target = document.getElementById("output"); target.innerHTML = "Germany"; } 
  <input type="button" value="click!" id = "myBtn" > <div id="output"></div> 

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