How to get which button is clicked?

旧巷老猫 提交于 2019-12-06 07:03:22

问题


I want to check some condition when a particular button is clicked how to do this?

 $(document).ready(function () {
         var prm = Sys.WebForms.PageRequestManager.getInstance();
         prm.add_initializeRequest(InitializeRequest);
         prm.add_endRequest(EndRequest);
         Search("Other");


     });

     function InitializeRequest(sender, args) {
     }

     function EndRequest(sender, args) {
         alert(sender._postBackSettings.sourceElement.id)
         var str1 = new String(sender._postBackSettings.sourceElement.id);
         if (sender._postBackSettings.sourceElement.id == ContentPlaceHolder1_btnNew) {
             alert("You have clicked new")
             Search("NEW"); 
         }

         else {
         alert("OTHERS")
             Search("Other");
          }


     }

回答1:


I got the solution by assigning it to a string value and checking in if condition as string.

 $(document).ready(function () {
         var prm = Sys.WebForms.PageRequestManager.getInstance();
         prm.add_initializeRequest(InitializeRequest);
         prm.add_endRequest(EndRequest);
         Search("Other");


     });

     function InitializeRequest(sender, args) {

     }

   function EndRequest(sender, args) {

         var str1 = new String(sender._postBackSettings.sourceElement.id);

         if (str1 == "ContentPlaceHolder1_btnNew") {                
            alert("You have clicked new")
         }

         else {
          alert("You have clicked others")
         }

     }



回答2:


If you have plenty of buttons, give them a same class name. Eg : class="myButton" The information regarding the particular button can be kept in its attribute. Eg : objectId="12345" then your code can come as follows :

$(".myButton").click(function(){
       console.log($(this)); // this gives you the DOM Object of the button which is clicked
       // now to get the attribute of the button i.e objectId you can do this
       $(this).attr("objectId");
       /* Depending on this you can handle your condition */
    });

If your buttons are being dynamically created, you can use this

$(".myButton").live('click', function(){
           console.log($(this)); // this gives you the DOM Object of the button which is clicked
           // now to get the attribute of the button i.e objectId you can do this
           $(this).attr("objectId");
           /* Depending on this you can handle your condition */
        });

live is deprecated for versions above Jquery 1.7.2.

You can use "on" instead of it.




回答3:


Try this code :

$(document).ready(function() {

    $("#btnSubmit").click(function(){
        // Call here that function which you want to call
    }); 
});

Read this link: http://api.jquery.com/click/



来源:https://stackoverflow.com/questions/23464375/how-to-get-which-button-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!