문제

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