dynamic radio buttons as navigation not working until page refresh

試著忘記壹切 提交于 2019-12-11 06:51:19

问题


I have a bunch of radio buttons, in a popup, that use the below to show and hide related divs, thus allowing them to be used as a form of navigation.

   $(":radio[name='radio']").on("change", function () {
        var test = $(this).val();
        $(".radio").hide();
        $("#" + test).show();
    });

This works find when I load the page, the code is contained within the

$('#gameIndex').on('pageshow', function (event, ui) {

However I also want to be able to dynanically add new radio buttons - the divs the button point to already exist on the page. I'm adding the buttons with:

$("#buttons").append('button code')

and then refreshing the div that contians the buttons with:

$("#radiodiv").trigger("create");

When I then trigger the popup with tte buttons they all appear as expected and are themed correctly. however when the buttons are clicked on they do nothing, they don't even seems to fire any kind of event. If I refesh the page they all start to work as expected.

Can any one please help me with this?


回答1:


Your current change binding:

$(":radio[name='radio']").on("change", function () {
    var test = $(this).val();
    $(".radio").hide();
    $("#" + test).show();
});

will not work retroactively on newly added elements, you need to use a delegated event binding for it to work:

$(document).on('change', ':radio[name="radio"]',function () {
    var test = $(this).val();
    $(".radio").hide();
    $("#" + test).show();
});



回答2:


use this code: Refrence
$(":radio[name='radio']").live("change", function() { var test = $(this).val(); $(".radio").hide(); $("#" + test).show(); });



来源:https://stackoverflow.com/questions/16495394/dynamic-radio-buttons-as-navigation-not-working-until-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!