Javascript 选择单选按钮的事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3761096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:02:37  来源:igfitidea点击:

Event for radio button being selected?

javascriptjquery

提问by Richard Knop

Is there some event for a radio button being selected?

是否有某个单选按钮被选中的事件?

I know I can use "click" but I believe it is possible to style radio buttons in some browsers such that clicking an outter area of a radio button might not select the radio button.

我知道我可以使用“单击”,但我相信可以在某些浏览器中设置单选按钮的样式,这样单击单选按钮的外部区域可能不会选择单选按钮。

What event should I use?

我应该使用什么事件?

回答by lincolnk

It depends when you want to be informed of the event.

这取决于您希望何时获知该事件。

If you want to know immediately, go with click. IE updates the state of checkedbefore the handler function is called, and I thinkthe other browsers do as well. You may want to double check as I only have IE to work with right now.

如果您想立即知道,请使用click。IE 会checked在调用处理函数之前更新状态,我认为其他浏览器也是如此。您可能需要仔细检查,因为我现在只有 IE 可以使用。

If you only need to know before something else happens, you can use change. IE will not fire the changeevent until the selected radio button loses focus. FF/chrome/others may fire the event without focus changing, but I believe IE is actually doing it right in this case.

如果您只需要在其他事情发生之前知道,您可以使用change. change在选定的单选按钮失去焦点之前,IE 不会触发该事件。FF/chrome/others 可能会在不改变焦点的情况下触发事件,但我相信 IE 在这种情况下实际上做得对。

回答by Daniel Vandersluis

You can use the onchangeevent, which will fire when the radio selection is changed (ie. the first time a radio button in the group is clicked or when the selection within the group is changed).

您可以使用该onchange事件,该事件将在单选选项更改时触发(即第一次单击组中的单选按钮或更改组内的选择时)。

See http://jsfiddle.net/P9Z9Y/1/for a simple example (clicking on either the label or the radio button itself will trigger an alertif the radio group's value changes).

有关简单示例,请参见http://jsfiddle.net/P9Z9Y/1/alert如果单选组的值发生变化,单击标签或单选按钮本身将触发)。

回答by Aaron Saunders

did you try using the onchange event?

您是否尝试使用 onchange 事件?

回答by Seph Reed

Not sure how new the inputevent is, but it's generally the best bet. Handles keyboard nav and the like. Updates immediately.

不确定活动有多新input,但通常是最好的选择。处理键盘导航等。立即更新。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event