在Ajax上动态创建后,Fire Radio Button按钮更改操作

发布于 2025-02-05 05:45:07 字数 980 浏览 4 评论 0原文

HI HI Stackoverflow社区,

我正在尝试与Ajax调用动态创建的无线电按钮的“更改”事件合作。这些无线电是根据MySQL结果创建的,每个广播按钮都应收听Onchange事件。

这是我的Ajax调用:

$.ajax({
        ...
        success:function(ajax_result){
            ajax_result.forEach(fn_Populate); // could be replaced with for loop
            function fn_Populate(element){
                $("xdiv").append("<input type='radio' id='radio_"+element[0]+"' name='xradio'>");
                $("xdiv").append("<label for='radio_"+element[0]+"'>"+element[0]+"</label>");
            }
        }
});

这应该根据AJAX结果,示例Radio_1,Radio_2,Radio_3创建无线电按钮,所有这些都带有 name xradio

创建无线电按钮后,我需要识别何时单击按钮。这是jQuery中的代码:

$("input[type=radio][name=xradio]").change(function(){
    alert("DO SOMETHING");
    // rest of code 
});

问题是,如果更改事件在Ajax呼叫之外,则不会触发。

我需要在Ajax呼叫之外发射它,因为它将通过新的Ajax调用生成另一个动态按钮。

所有的帮助将不胜感激。

谢谢

Hi stackoverflow community

I'm trying to work with the on change event of radio buttons that are created dynamically from an ajax call. These radios are created based on a MySQL result and each radio button should listen to an onChange event.

Here is my ajax call:

$.ajax({
        ...
        success:function(ajax_result){
            ajax_result.forEach(fn_Populate); // could be replaced with for loop
            function fn_Populate(element){
                $("xdiv").append("<input type='radio' id='radio_"+element[0]+"' name='xradio'>");
                $("xdiv").append("<label for='radio_"+element[0]+"'>"+element[0]+"</label>");
            }
        }
});

This should create the radio buttons according to the ajax result, example radio_1, radio_2, radio_3, all with name xradio.

After the radio buttons are created, I need to identify when a button is clicked. Here is the code in jquery:

$("input[type=radio][name=xradio]").change(function(){
    alert("DO SOMETHING");
    // rest of code 
});

The problem is that the change event is not fired if it is outside of the ajax call.

I need to fire it outside of the ajax call because it will generate another dynamic button through a new ajax call.

All help will be appreciated.

Thanks

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

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

发布评论

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

评论(1

草莓味的萝莉 2025-02-12 05:45:07

考虑以下内容。

$("#xdiv").on("change", "input[name=xradio]", function(event){
  console.log("Change on " + $(this).attr("id"));
});

这是使用委托将事件回调绑定到动态元素的静态元素的静态元素。该委托可以由子元素触发。

请参阅更多: https://api.jquery.com/on/

Consider the following.

$("#xdiv").on("change", "input[name=xradio]", function(event){
  console.log("Change on " + $(this).attr("id"));
});

This is using delegation to bind the event callback to a static element that is the parent of the dynamic element. The delegation allows it to be triggered by the child element.

See More: https://api.jquery.com/on/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文