单击动态生成的单选按钮 [英] Click on dynamically generated radio button

查看:60
本文介绍了单击动态生成的单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在选中动态生成的单选按钮时提醒一些文本..这是小提琴的链接. http://jsfiddle.net/z7cu3q0y/

i am trying to alert some text when a dynamically generated radio button is checked .. here is the link from fiddle .. http://jsfiddle.net/z7cu3q0y/

function createRadioButtons(n)
{
    $("#radioContainer").empty();
    for(var i=0;i<n;i++)
    {
        radioButtons = "<p><input type='radio' class='"+n+"' name='"+n+"'>"+(i+1)+"</p>";
        $("#radioContainer").append(radioButtons);
    }
}    

$("#dropDown").on("change",function()
{
      createRadioButtons(parseInt($(this).val()));
});

$("#radioContainer input").on("change",function()
{
      alert("checked");
});

当我单击单选按钮时,我没有收到警报..你们中的任何一个可以帮助我看看吗?

when i click on radio button i am not getting alert .. can any one of you please help me in taking a look ?

预先感谢, 阿什温

推荐答案

您的代码$("#radioContainer input").on("change",function(){}) 会将事件处理程序直接附加到DOM中当前存在的匹配元素.

Your code $("#radioContainer input").on("change",function(){}) will directly attach the event handler to the matching elements that are currently present in DOM.

要使用将来添加的动态生成的元素,您需要委托将事件处理程序添加到公共父元素:

To work with dynamically generated elements added in the future, You need to delegate your event handler to a common parent element:

$("#radioContainer").on("change","input",function(){
  alert("checked");
});

上面将把处理程序附加到#radioContainer,每当触发相应的事件(在这种情况下为 change )(通常从子对象传播),它会检查事件目标是否与指定的选择器(在这种情况下为 input )匹配,并相应地调用处理程序.

The above will attach the handler to #radioContainer, Whenever the corresponding event (change in this case)is triggered (Usually propagated from the children), it checks whether the event target matches the specified selector (input in this case) and invokes the handler accordingly.

更新了小提琴

这篇关于单击动态生成的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆