简体   繁体   中英

onclick not working on button

When I click a button "click Me" on my page. I want to know that the button is clicked and an alert should pop up saying hi.Here is my code which is not working.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn").click(function(){
  $(this).data('clicked', true);
     });
if($('#btn').data('clicked')) {
alert("HI");
}
});
</script>
</head>
<body>
<input id="btn" value="Click Me" type="button"></input>
</body>
</html>

Move the alert to inside the handler:

$("#btn").click(function(){
    $(this).data('clicked', true);
    if($(this).data('clicked')) {
        alert("HI");
    }
});

That if statement doesn't automatically run (well it does on page load since it's in your DOM ready event) - it has to be within an event.

You could drop the if statement at all. It's key to put your alert() call in the click Callback function.

$(document).ready(function(){
  $("#btn").click(function(){
      alert("HI");
   });
});

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