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

Ahm*_*rid 118 jquery

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

<!-- Begin Button -->  
<div class="demo">
<br> <br> <br>   
<input id = "btnSubmit" type="submit" value="Release"/>
<br> <br> <br>  
</div>
<!-- End Button -->
Run Code Online (Sandbox Code Playgroud)

并在JavaScript文件中

function btnClick()
{
    //    button click
    $("#btnSubmit").button().click(function(){
        alert("button");
    });    
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ano 227

您必须将事件处理程序放在$(document).ready()事件中:

$(document).ready(function() {
    $("#btnSubmit").click(function(){
        alert("button");
    }); 
});
Run Code Online (Sandbox Code Playgroud)


小智 23

$(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;
     });


});
Run Code Online (Sandbox Code Playgroud)

  • 从jQuery 1.7开始,`.on()`方法是将事件处理程序附加到文档的首选方法.因此,这会更好:`$('你的选择器').on("click",...);` (12认同)
  • 好,因为是唯一插入preventDefault()的人 (4认同)

小智 7

尝试这个:

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


Ali*_*ini 6

 $("#btnSubmit").click(function(){
        alert("button");
    });    
Run Code Online (Sandbox Code Playgroud)


小智 5

$('#btnSubmit').click(function(){
    alert("button");
});
Run Code Online (Sandbox Code Playgroud)

要么

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

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