在单选按钮上执行 onChange 函数

Posted

技术标签:

【中文标题】在单选按钮上执行 onChange 函数【英文标题】:On Radio Button execute onChange function 【发布时间】:2019-09-20 22:56:50 【问题描述】:

我得到了(工作的)以下代码

$('#selBookable').change(function () ...

 <div class="radio radio-search">
  <label><input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" >Neueste</label>

当#selBookable 获得另一个值时执行。

现在我想在单击其他地方的单选按钮时执行此功能。

我试过了:

$('#selBookable, #radio-new-pop').change(function () ...

但这不起作用。 现在我想给这个“.change(function NAMEHERE” 一个名称并执行该功能,但也不起作用。 任何帮助表示赞赏。

编辑:我尝试使用 onchange 事件,但我又没有要调用的函数名。

【问题讨论】:

【参考方案1】:

你可以独立于它的使用来定义函数,给它一个名字。然后,您可以将它附加到任意数量的目标上,调用有效的目标(使用名称而不是定义),每个目标都有不同的目标。

(您第二次尝试失败的原因是$ 的第二个参数不是将函数附加到的另一个目标,而是对在哪里找到第一个目标的约束。)

【讨论】:

我想,这就是我尝试以下方法的原因:$('#selBookable').change(name); $('#radio-new-pop').change(name); function name() 第一个有效,第二个无效。【参考方案2】:

你有两个同名的按钮单选:

<div class="radio radio-search">
    <label>
        <input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" />
        Neueste
    </label>
    <label>
        <input id="radio-new-pop2" type="radio" name="radio_newest_popular" value="new" />
        Other
    </label>
</div>

添加一个javascript函数来处理这个变化:

var onRadioButtonChange = void 0;

    onRadioButtonChange = function (e) 
        theFunctionYouWantToExecute(); // pass this or e.target if needed
        return false;
    

将其附加到您的元素:

Array.prototype.forEach.call(
    document.querySelectorAll('input[type="radio"]'), 
    function (element)  
        element.addEventListener('change', onRadioButtonChange, false); 
    
);

【讨论】:

【参考方案3】:

也许尝试将 jquery 侦听器放在 $(document).ready() 中。

您可以在收音机上添加click 处理程序,如下所示:

    <div class="radio radio-search">
        <label>
            <input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" onclick="handleClick(this)">
        Neueste</label>

在 JS 中:

    handleClick(myRadio) 
        // click function logic
    

改编自this答案。

【讨论】:

顺便你也可以onclick="this.onchange"

以上是关于在单选按钮上执行 onChange 函数的主要内容,如果未能解决你的问题,请参考以下文章

是否可以在单选按钮悬停时调用函数并使用 jQuery 显示在工具提示中返回的信息

Javascript:如何让单选按钮的“onchange”事件通过外部函数触发?

.click() 在单选按钮上不起作用

在单选按钮组上使用数据属性来显示文本

如何在单选按钮上绑定数据

如何使用 UIView 在单选按钮上制作多行标题