简体   繁体   English

onclick不起作用的按钮

[英]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: alert移至处理程序内部:

$("#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. if语句不会自动运行(因为它在DOM ready事件中,所以它会在页面加载时执行)-它必须在一个事件内。

You could drop the if statement at all. 您可以完全删除if语句。 It's key to put your alert() call in the click Callback function. 将您的alert()调用放入点击回调函数中的关键。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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