I am wondering if someone can help me out with this.
I have a button defined as:
<input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/>
I can use jQuery, standard javascript or Dojo to disable the button with onClick event:
$('#myButton').attr('disabled', 'disabled');
The problem I am facing is, even th开发者_如何转开发ough this code disables the button, onClick event still triggers the function callMe()
if I click on the button.
How do I make the disabled button not call the onClick function?
With jQuery you can bind a function that checks if your button is disabled:
$('#myButton').click(function() {
if (!$(this).is(':disabled')) {
callMe();
}
});
Since you're using jQuery, use
$('#myButton').click(function() { callMe(); this.unbind(); });
instead of onClick.
$('#myButton').click(function(){
if( !$(this).is('[disabled=disabled]') ){
...
}
});
In the same code where you disable it, simply remove the onclick event handler.
instead of using onclick attribute, bind to the event
$('#myButton').click(function(e){
// try it without this
if($(this).attr('disabled'))
return false;
callMe();
e.preventDefault();
});
try it without the check, not sure if its necessary.
This is one way of doing.
$('#myButton').click(function(){
if(!$(this).hasClass("disabled")){
//Do stuff here
}
});
To disable the buttons just add the disabled class to it.
$('#myButton').addClass("disabled");
Add appropriate styles in the disabled class to make button look like disabled or you can also set the disabled property along with setting the class.
you should be using jQuery to attach the click handlers, not adding them inline*
Just add a check to your click function
$('#myButton').click(function(){
var $this;
$this = $(this);
if ( $this.is(':disabled') ) return;
callMe();
});
Alternatively,
$('#myButton').click(callMe);
callMe()
{
var $this;
$this = $(this);
if ($this.is(':disabled')) return;
...the rest of your code...
}
Or if you insist on using it inline:
onclick="if ($(this).is(':disabled')) return; callMe();"
* I regularly rant about how HTML, CSS & JS fit the definition of MVC
Instead of ...
$('#myButton').attr('disabled', 'disabled');
... use ...
$('#myButton')
.prop('disabled', 'disabled') // Sets 'disabled' property
.prop('onclick', null) // Removes 'onclick' property if found
.off('click'); // Removes other events if found
精彩评论