如何处理jQuery中的按钮单击事件?


128

我需要有一个按钮并在jQuery中处理其事件。而且我正在编写此代码,但无法正常工作。我错过了什么?

<!-- Begin Button -->  
<div class="demo">
<br> <br> <br>   
<input id = "btnSubmit" type="submit" value="Release"/>
<br> <br> <br>  
</div>
<!-- End Button -->

并在javascript文件中

function btnClick()
{
    //    button click
    $("#btnSubmit").button().click(function(){
        alert("button");
    });    
}

1
为什么不将其从封闭btnClick功能中删除呢?我看不到有什么增加
CodyBugstein 2014年

Answers:



25
$(document).ready(function(){

     $('your selector').bind("click",function(){
            // your statements;
     });

     // you can use the above or the one shown below

     $('your selector').click(function(e){
         e.preventDefault();
         // your statements;
     });


});

5
很好,因为是唯一插入preventDefault()的人
Gabrer 2014年

12
从jQuery 1.7开始,该.on()方法是将事件处理程序附加到文档的首选方法。因此,这样会更好:$('your selector').on("click", ...);
Tinynumbers 2015年

11
$('#btnSubmit').click(function(){
    alert("button");
});

要么

//Use this code if button is appended in the DOM
$(document).on('click','#btnSubmit',function(){
    alert("button");
});

有关更多信息,请参见文档:https :
//api.jquery.com/click/


如果使用诸如sweetalert之类的通知,则在dom事物中附加的按钮始终是一个问题。谢谢指点出来
Deepesh塔帕


5

试试这个:

$(document).on('click', '#btnClick', function(){ 
    alert("button is clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <button id="btnClick">Click me</button> 


如果在此脚本运行后创建了#btnClick,则此版本的优点是仍然可以工作。
金巴利

3
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
  $("#button").click(function(){
    alert("Hello");
  });
});
</script>

<input type="button" id="button" value="Click me">


1
$('#btnSubmit').click(function(event){
    alert("Button Clicked");
});

或使用提交按钮时,您可以在表单的validate事件中编写代码,例如

$('#myForm').validate(function(){
    alert("Hello World!!");
});

0

为我工作

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

$("#btn").click(function() {
    alert("email")
});

</script>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.