如何在 JS 中找到单选按钮的上一个/默认值?

发布于 2024-08-30 01:54:37 字数 437 浏览 2 评论 0原文

我不确定这是否可能,但我想在联合提出一个丑陋的解决方案之前我应该​​先问一下。

我拥有的是一组单选按钮,我想在单选按钮值更改时触发一个功能。例如,有 XY 和 Z 三个按钮,默认选择 Y。如果用户单击未选择的按钮(即 X 或 Z),则会触发该功能,但如果他/她单击 Y(已选择)则不会发生任何情况。

当然,最好的解决方案是在 onchange 事件上触发该函数,但 IE6 不会触发 onchange,直到焦点不再位于不令人满意的元素上。

那么有没有办法知道单选按钮以前的值是什么或者至少知道它的默认值是什么?我可以轻松创建默认值数组并进行检查,但我正在努力减少开销。

请不要 jQuery 建议 ;)

I'm not sure if this is even possible, but I figured I'd ask before clubbing togehter an ugly solution.

What I have is a group of radio buttons and I want to trigger a function if the radio button value is changed. For example say there are three buttons X Y and Z with Y default selected. If a user clicks on an unselected button (i.e. X or Z) then the function gets triggered but if he/she clicks on Y (which is already selected) nothing happens.

Naturally the best solution would be to fire the function on an onchange event but IE6 doesn't fire onchange until the focus is no longer on the element which is not satisfactory.

So is there a way to know what the previous value of the radio button was or at least what its default value is? I could easily create an array of default values and check against that but I'm trying to reduce the overhead.

Please no jQuery suggestions ;)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

私藏温柔 2024-09-06 01:54:37

使用输入元素的defaultChecked 属性。

您还可以为此使用 click 事件,因为当用户使用空格键/回车键来“检查”它时,也会触发 click 事件。

Use the defaultChecked property of the input element.

You could also use the click event for this, because click event fires also when the user uses the spacebar/enter key on it to "check" it.

羁拥 2024-09-06 01:54:37

好吧,您可以在输入元素上使用 onmousedown 事件。它会执行您所要求的操作(当用户单击时激活事件),但是使用 onmousedown,您可以检查该元素是否已被选择。例子:

document.getElementById('#radio-button-x').onmousedown = function() {
    if (this.checked == true) {
        // was already selected
    } else {
        // not selected, do something
    }
};

Well, you could use the onmousedown event on the input elements. It would do what you're asking (activate an event when the user clicks), but with onmousedown, you can check if the element was already selected. Example:

document.getElementById('#radio-button-x').onmousedown = function() {
    if (this.checked == true) {
        // was already selected
    } else {
        // not selected, do something
    }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文