为什么当我在复选框上触发"change"事件时,事件对象没有使用新状态更新



我有两个元素。出于某种原因,我无法触发复选框上的更改事件,也无法将有关复选框新状态的信息传递给事件方法。

为什么在调用事件时,选中的属性不能正确显示?

// this works perfectly fine. UI updates. The event method is called and the event e contains the new checked property
$('#mycheckbox').on('change', this.onCheckboxClicked.bind(this));
// this works only partially. UI gets updated. The event methos is called but the event e doesn't contain the checked property.
$('#sometext').on('click', () => $('#mycheckbox').trigger('change'));
function onCheckboxClicked(e) {
// display true when i click on the checkbox but false when i click on the span. Why ?
console.log($(e.target).prop('checked'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="mycheckbox" />
<span id="sometext">My Text</span>

问题是您正在触发change事件,但不会更新复选框的checked状态。如果将$('#mycheckbox').trigger('change')更改为$('#mycheckbox').trigger('click'),它应该可以工作。

不过我必须说,你可以使用:

<label for="mycheckbox">My Text</label>

以达到相同的效果。

$('#mycheckbox').trigger('change')更改为$('#mycheckbox').trigger('click')

为了给那些不使用鼠标的用户提供更好的用户体验,已经开发了浏览器来触发onclick事件,即使点击keyboard一起发生。

因此,jQuery的

  1. click事件将触发,即使使用键盘的空格键单击复选框也是如此
  2. 每当复选框的状态发生变化时,change都会激发

复选框恰好是更改和单击可以互换的特殊情况,因为您不能在不触发单击的情况下触发更改事件。

$('#mycheckbox').on('change', this.onCheckboxClicked.bind(this));
$('#sometext').on('click', () => $('#mycheckbox').trigger('click'));
function onCheckboxClicked(e) {
console.log($(e.target).prop('checked'));
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<input type="checkbox" id="mycheckbox" />
<span id="sometext">My Text</span>

当我这样做的时候,它对我有效。不知道为什么,但使用jquery 3.5和一种引导风格的输入的点击方法没有奏效。

$('#sometext').on('click', () => Promise.resolve().then(() => $('#mycheckbox').trigger('change')));

更新

似乎当另一个EventHandler附加到同一个元素时,例如,如果我有以下内容:

<input type="checkbox" class="mycheckbox" id="mycheckbox" />
<span id="sometext" class="myspan">My Text</span>

然后

$('#mycheckbox').on('change', this.onCheckboxClicked.bind(this));
// even though .myspan is a different class, the event is attached to the 
// same DOM object which not only generates the issue described in the 
// question but also will nullify the solution in the answer proposed.
$('.myspan').on('click', this.onAnotherMethodClicked.bind(this));
$('#sometext').on('click', () => $('#mycheckbox').trigger('change'));

最新更新