質問

I create a new div from post response. This div has a button and I want to assign a click event to it. It doesn't work if I the script part is in the response

<script>
    $(document).ready(function(){
        alert('test1');
        $('#next2').click(function(){
            alert('test2');
        });
    });
</script>

alert('test1') works, test2 on click doesn't bind

Binding only works if put in $.post(...).always (function..) but I'd like to have the binding in the same place as the rest of the loaded element to be flexible.

役に立ちましたか?

解決

you need event delegation for dynamically created element.use .on():

$(document).on('click','#next2',function(){
        alert('test2');
 });

他のヒント

You can use on() with document scope for a dynamically created elements

  $(document').on('click',''#next2',function(){
        alert('test2');
    });

If you want to target a dynamically added element you'll have to use

<script>
        $(document).ready(function(){

            $('#next2').on("click",function()
                alert('test2');
            });
        });
    </script>

You can use,

<script type="text/javascript">
$('#next2').bind('click',function(){
        alert('test2');
});
<script>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top