Apply jquery code on all elements

2019-07-25 11:02发布

问题:

how can I apply a jquery function to elements that are loaded with ajax?

<span class="h">Test</span><br /><br />
<span class="h">Test</span><br /><br />
<span class="h">Test</span><br /><br />
....
<span class="h">Test</span><br /><br />
<script type="text/javascript">
    $(document).ready(function() {
    $('.h').click(function() {
        alert("test");
    });
});
</script>

So, this works perfectly. Every click on a span element returns an alert. But there the click function is not applied to the elements loaded with ajax:

<span class="h">Test</span><br /><br />
<span class="h">Test</span><br /><br />
<span class="h">Test</span><br /><br />
....
<span class="h">Test</span><br /><br />
<script type="text/javascript">

    $(window).scroll(function(){
    if  ($(window).scrollTop() == $(document).height() - $(window).height()) {
        $('body').append('<span class="h">Test3</span><br /><br />');
    }
    });

    $(document).ready(function() {
    $('.h').click(function() {
        alert("test");
    });
});
</script>

How can I solve that issue?

回答1:

jQuery's live() is what you'll want:

$('.h').live('click', function () {
  // Do something!
}


回答2:

The click() function only adds a listener to the elements present at th time it was called. You need to call it again on any element, you add later on.

Or, as @jerluc stated, use the live() function.



回答3:

You must use live instead of click, so that the event is binded also to newly appended items:

$('.h').live('click', function() {
    alert("test");
});


回答4:

You need the live function to bind the event to elements created dynamically:

$('.h').live('click', function() {
    alert("test");
});


回答5:

You aren't reapplying the behaviour. You need to use jQuery's live method to keep checking the DOM for new elements.

Demonstration of live



回答6:

     $(document).ready(function() {
         $('.h').live('click', function() {
            alert("test");
         });
     });