Apply jquery code on all elements

2019-07-25 10:26发布

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?

6条回答
爷的心禁止访问
2楼-- · 2019-07-25 11:03

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

查看更多
孤傲高冷的网名
3楼-- · 2019-07-25 11:05

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楼-- · 2019-07-25 11:11

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

$('.h').live('click', function() {
    alert("test");
});
查看更多
小情绪 Triste *
5楼-- · 2019-07-25 11:15

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.

查看更多
Emotional °昔
6楼-- · 2019-07-25 11:21

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

$('.h').live('click', function () {
  // Do something!
}
查看更多
来,给爷笑一个
7楼-- · 2019-07-25 11:29
     $(document).ready(function() {
         $('.h').live('click', function() {
            alert("test");
         });
     });
查看更多
登录 后发表回答