我有一个表格。我只想在用户精确选中 8 个可用复选框中的 4 个时允许表单提交;一旦用户选中 4 个复选框,我想禁用其余未选中的复选框。
我应该在 click
添加一个钩子(Hook)吗?事件?或者也许是input
事件?或者也许是change
事件?
大量的事件似乎彼此重复功能,这让我不知所措。
我也对文档感到困惑。
For
<input>
elements withtype=checkbox
ortype=radio
, theinput
event should fire whenever a user toggles the control, per the HTML5 specification. However, historically this has not always been the case. Check compatibility, or use thechange
event instead for elements of these types.
Unlike the
input
event, thechange
event is not necessarily fired for each alteration to an element'svalue
.
以及下面:
Depending on the kind of element being changed and the way the user interacts with the element, the
change
event fires at a different moment:
- 当元素为
:checked
时(通过单击或使用键盘)<input type="radio">
和<input type="checkbox">
;
An element receives a
click
event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
练习:
下面的 JS fiddle 似乎暗示所有 3 个事件是等效的。单击复选框、单击标签、聚焦复选框以及按键盘上的空格似乎都会触发所有三个事件。
const checkbox = document.querySelector('input[type=checkbox]');
for (const event of ['input', 'click', 'change']) {
checkbox.addEventListener(event, () => {
log.textContent = `${event}\n${log.textContent}`
})
}
<label>Toggle <input type="checkbox" name="" id="">
</label>
<pre id="log"></pre>
根据文档 change
和input
看起来相当; click
根据文档,似乎与其他 3 个并不等效,但实际上它似乎是等效的。
我们真的有 3 个功能重复的事件吗?我使用哪个事件有什么关系吗?
或者我错过了什么?
最佳答案
这 3 个事件彼此重复功能,因为您正在查看的复选框恰好是一种特殊情况。
例如,如果您要使用文本字段
- 只要使用用户界面更改元素中的文本,就会触发
input
事件。 - 每当文本元素失去焦点时,
change
事件就会触发(在大多数浏览器上)。它只会触发一次,而不是每次击键后触发。 - 只要用户单击文本字段,
click
事件就会触发。
如果我们将此应用于复选框(请记住,复选框只能更改为一件事:checked => unchecked
或unchecked =>Checked
)
- 每当使用用户界面更改选中状态时,
input
事件就会触发。 - 每当选中状态发生更改时,都会触发事件
change
在元素 (or when the checkbox loses focus in IE) 中。 - 检查状态完成更改后,将触发事件
click
。
这 3 个事件具有非常相似的功能(几乎重复),因为它们都试图做一些不同的事情,而这些事情在功能上对复选框执行相同的操作。唯一的区别是细微的实现细节。
我会使用click
来避免不同浏览器的用户遇到问题。
关于javascript - 单击、输入、更改复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58016503/