简体   繁体   English

是否可以更改复选框状态而不会导致单击事件?

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

I'm trying to find a way to prevent input[type='checkbox'] from triggering the click event when I change his state with jquery. 我试图找到一种方法来阻止input[type='checkbox']在我用jquery更改状态时触发click事件。

Is it possible? 可能吗?

If you use .prop() on the checked attribute, no click event will be triggered: 如果在checked属性上使用.prop() ,则不会触发任何click事件:

$("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 http://jsbin.com/ecIQUle/3/edit

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> 从事件处理程序返回false<input type=checkbox onclick="return false;"></input>
  • Using jQuery's preventDefault 使用jQuery的preventDefault
  • Using jQuery's stopPropagation 使用jQuery的stopPropagation

with the last likely being more correct. 最后可能更正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM