开发者

Trouble binding jquery javascript click event to asp.net button

开发者 https://www.devze.com 2023-01-24 07:11 出处:网络
Im using the following code: jQuery(document).ready(function () { jQuery(\'<%= btnSave.ClientID %>\').click(function(){

Im using the following code:

jQuery(document).ready(function () {

jQuery('<%= btnSave.ClientID %>').click(function(){

    alert('hello world');

});

});

And when I click the asp.net button:

开发者_如何学Python
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />

It just doesnt fire. Anybody know why?

Cheers, Pete


jQuery(document).ready(function () {

jQuery('#<%= btnSave.ClientID %>').click(function(){

    alert('hello world');
});

});

And why you put .ClientID?? in the asp you dont put any class to the button

Sorry for my english


Hi Sorry I figured it out it needs a pound sign before the selector!

 jQuery(document).ready(function () {

jQuery('#<%= btnSave.ClientID %>').click(function(){

    alert('hello world');

});

});


Another alternative here is to use a class so you can move your code externally, for example:

<asp:Button ID="btnSave" CssClass="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />

Then your code can look like this:

jQuery(function($) {
  $('.btnSave').click(function() {
    alert('hello world');
  });
});

Which can be in an external .js, so your users download it once, not as part of the page each time. Alternatively, a bit less efficient is to use the attribute ends-with selector, like this:

jQuery(function($) {
  $('input[id$=btnSave]').click(function() {
    alert('hello world');
  });
});

This will select all <input> elements that have an ID ending in btnSave.

0

精彩评论

暂无评论...
验证码 换一张
取 消