How can I can I get the correct current value in the click event to call via a trigger?
Html:
<input type="checkbox" id="mycheck" />
<br />
<span id="actual-value-inevent"></span>
<br />
<span id="actual-value"></span>
<br />
<button id="view-value">view value</button>
<br />
<button id="call-trigger">call trigger</button>
<br />
<button id="call-trigger-handler">call trigger handler</button>
Javascript:
$('#mycheck').bind('click', function(ev) {
$('#actual-value-inevent').html('value in event : ' + $(this).is(':checked'));
});
$('#view-value').bind('click', function(ev) {
$('#actual-value').html('value view : ' + $('#mycheck').is(':checked'));
});
$('#call-trigger').bind('click', function(ev) {
$('#mycheck').trigger('click');
$('#actual-value').html('value post trigger: ' + $('#mycheck').is(':checked'));
});
$('#call-trigger-handler').bind('click', function(ev) {
$('#mycheck')[0].checked = !$( "input" )[ 0 ].checked;
$('#mycheck').triggerHandler('click');
$('#actual-value').html('value post triggerHandler: ' 开发者_JAVA技巧+ $('#mycheck').is(':checked'));
});
If I call the "trigger ('click')", in the event the current value of the checkbox is pre-click.
On this blog I find a solution, but I need to solve the problem in the function of the event, not to call the trigger.
example
example with solutionpossible solution by overriding the trigger method:
(function($){
var triggerOverwrite = $.fn.trigger;
$.fn.trigger = function (eventType, extraParameters) {
var stringEvent = '';
if (typeof eventType == 'string')
stringEvent = eventType;
else
stringEvent = eventType.type;
if (this.get(0).tagName.toLowerCase() == 'input'
&& stringEvent == 'click' && $(this).attr('type') == 'checkbox')
{
$(this)[0].checked = !$(this)[0].checked;
return $(this).triggerHandler(stringEvent, extraParameters);
}
return triggerOverwrite.apply(this, arguments);
};
})(jQuery);
run
The click event applied to the check box is run before the click makes any changes.
So in your check box click event do the following:
$('#mycheck').bind('click', function(ev) {
$('#actual-value-inevent').html('value in event : ' + !$(this).is(':checked'));
});
精彩评论