dsqnonh2763 2014-08-17 08:07
浏览 28
已采纳

更改通过ajax加载的无线电组的功能

jquery change function on radio button is working properly when they are part of html body i.e when they have written in html body, but when they loaded through ajax request change function not works. My code is- html code

<form>
    <select id="sel" name="sel">
        <option value="">Select Type</option>
        <option value="1">1</option>
        <option value="2">2</option>
    </select>

    <div id="load"></div>   
    <label id="change">--</label>
</form>

<script type="text/javascript">
    $(document).ready(function(){
        $('.radi').change(function(){
            console.log( "radio clicked!" );
            $('#change').html("Loaded2: ");
        });

        $("#sel").change(function(){
            var id=$(this).val();
            var dataString = 'id='+ id;
            $.ajax ({       
                type: "POST",
                url: "faculty.ajax_load.php",
                data: dataString,
                cache: false,
                success: function(html){
                    $("#load").html(html);
                    console.log( "radio loaded" );  
                }
            });
        });
    });
</script>

ajax_load.php is:-

<?php

    echo '<input class="radi" type="radio" name="sect" value="P" id="p"/>
    <input type="radio" class="radi" name="sect" value="A" id="a" checked="checked"/>';

?>

Now the problem is radio buttons are appear but when I click them change is not shown on console and label. Please help, where I am doing mistake.

  • 写回答

1条回答 默认 最新

  • dpswo40440 2014-08-17 08:08
    关注

    Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

    As you are loading using ajax call.

    You need to use Event Delegation. You have to use .on() using delegated-events approach.

    Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

    General Syntax

    $(document).on(event, selector, eventHandler);
    

    Ideally you should replace document with closest static container.

    As per your code

    $("#load").on('change', '.radi', function(){
        console.log( "radio clicked!" );
        $('#change').html("Loaded2: ");
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?