简体   繁体   中英

How can i run jQuery on content added dynamically?

I made a page which is really similar to Facebook wall page: there are some posts, a list of comments for each post and a "send" button, for each post, to send a new comment.

In the following example:

  1. The post is identified with the class "mypost".
  2. The post-new-comment button is the div with class "send-comment".
  3. Once you scroll to the bottom, more posts are loaded dynamically with a script i didn't write here.
  4. When you click on "send-comment" a script is called and the comment is added to database.

Here is a portion of the page.

<!--my first post-->
<div id="div1" class="mypost">
    <div class="send-comment"></div>
</div>
<!--my second post-->
<div id="div2" class="mypost">
    <div class="send-comment"></div>
</div>

<!--my js code-->
<script text="type/javascript">
    $('.send-comment').click(function(){
        //send comment
    });
</script>

When the user scrolls down the page, other posts are injected into the page and this is the result:

<!--my first post-->
<div id="div1" class="mypost">
    <div class="send-comment"></div>
</div>
<!--my second post-->
<div id="div2" class="mypost">
    <div class="send-comment"></div>
</div>
<!--third post, added dynamically with jQuery-->
<div id="div3" class="mypost">
    <div class="send-comment"></div>
</div>

<!--my js code-->
<script text="type/javascript">
    $('.send-comment').click(function(){
        //send comment
    });
</script>

The problem is the following: The script to send comments is working like charm on the existing divs, but on every div added dynamically, nothing works. No clicks are detected. Nothing happens.

More generally, I can't find a way to make any kind of script work on divs (or any other html tag) added after a user action.

Cany anybody suggest a solution to fix this problem?

Try this:

<script text="type/javascript">
    $(document).on('click', '.send-comment', function(){
        //send comment
    });
</script>

on allows you to attach handlers to elements, even if they don't yet exist in the DOM. ref: http://api.jquery.com/on/

You might want to replace document from this binding function, it is usually overly broad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM