Is it possible to change checkbox state without causing click event?

房东的猫 提交于 2019-12-24 10:56:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!