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