为什么 jQuery .change() 不会在因选择同名而取消选择的单选按钮上触发?
如果我有多个同名的单选按钮,则每次只能选择一个。当其中一人被选中时,任何同名者都会失去其选择权。我很好奇为什么这不构成 jQuery 的 .change()
事件。
破解 $.change()
函数将是相当激烈的,但这似乎并没有被报告为错误 - 所以我有兴趣找出为什么情况并非如此。
下面的测试:我希望每当选择无线电时都会触发两个更改事件,但事实并非如此。
If I have several radio buttons of the same name, only one can be selected at any one time. When one becomes selected, any namesakes lose their selection. I'm intrigued as to why this doesn't constitute a .change()
event for jQuery.
Hacking the $.change()
function would be pretty drastic, but this doesn't seem to be reported as a bug — so I'm interested in finding out why this isn't the case.
Test below: I'd expect the two change events to fire whenever a radio is selected, but that isn't the case.
Here is the example: http://jsfiddle.net/XzmmW/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您将一组单选按钮视为
select
元素,那么为什么没有必要为取消选择的单选按钮触发更改事件就变得很清楚了。当您更改
select
元素中的选定选项时,您会收到一个更改事件(您不会期望其他任何事件),而不是一个针对先前选定的选项的事件,以及另一个针对新选定的选项的事件。正如已经提到的,当选择一个单选按钮时,同一组中的其他单选按钮不能被选择,因此触发第二个更改事件是多余的。
另请注意,这并不是 jQuery 特有的 - 标准 JavaScript 更改事件的工作方式完全相同。
If you think of a set of radio buttons like a
select
element, it becomes clear why it's unnecessary to fire a change event for the deselected radio button.When you change the selected option in a
select
element, you get one change event (you wouldn't expect anything else), rather than one for the previously selected option, and another for the newly selected option.As has already been mentioned, when one radio button is selected, no others in the same set can be, so it would be redundant to fire a second change event.
Also note that this is not specific to jQuery - the standard JavaScript change event works in exactly the same way.
只有 1 个更改事件...您从“旧选择”更改为“新选择”。
请记住,虽然您有多个“元素”,但它们都是相同表单元素的一部分(由
name
属性定义)。There is only 1 change event... you changed from "old selection" to "new selection".
Keep in mind that although you have multiple "elements" they are all part of the same form element (as defined by the
name
attribute).无需为命名组中的每个单选按钮触发事件,当选择一个单选按钮时,您知道其他按钮未被选择
There is no need to fire an event for each radio button in a named group, when one is selected you know the others are not selected