问题
I'm trying to find a way to prevent input[type='checkbox']
from triggering the click
event when I change his state with jquery.
Is it possible?
回答1:
If you use .prop()
on the checked
attribute, no click event will be triggered:
$("input[type='checkbox']").click(function() {
alert('checkbox clicked');
});
$('#mycheckbox').prop('checked', true);
$('#mycheckbox').prop('checked', false);
$('#mycheckbox').prop('checked', true);
$('#mycheckbox').prop('checked', false);
$('#mycheckbox').prop('checked', true);
http://jsbin.com/ecIQUle/3/edit
回答2:
Depending on what you're trying to do, one of the following may help:
- Returning
false
from an event handler:<input type=checkbox onclick="return false;"></input>
- Using jQuery's preventDefault
- Using jQuery's stopPropagation
with the last likely being more correct.
来源:https://stackoverflow.com/questions/19484140/is-it-possible-to-change-checkbox-state-without-causing-click-event