如何获得点击的按钮?

我想在点击特定按钮时查看某些条件如何执行此操作?

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

我通过将其分配给字符串值并检查条件是否为字符串来获得解决方案。

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

如果你有足够的按钮,给他们一个相同的类名。 例如:class =“myButton”有关特定按钮的信息可以保存在其属性中。 例如:objectId =“12345”那么你的代码可以如下:

 $(".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 ie objectId you can do this $(this).attr("objectId"); /* Depending on this you can handle your condition */ }); 

如果您的按钮是动态创建的,则可以使用此按钮

 $(".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 ie objectId you can do this $(this).attr("objectId"); /* Depending on this you can handle your condition */ }); 

对于Jquery 1.7.2以上的版本,不推荐使用live。

您可以使用“on”代替它。

试试这段代码:

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

阅读此链接: http : //api.jquery.com/click/