简体   繁体   English

如何在动态添加的内容上运行jQuery?

[英]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. 我制作了一个页面,该页面与Facebook墙面页面非常相似:有一些帖子,每个帖子的评论列表,以及每个帖子的“发送”按钮,用于发送新评论。

In the following example: 在以下示例中:

  1. The post is identified with the class "mypost". 该帖子的类别为“ mypost”。
  2. The post-new-comment button is the div with class "send-comment". 新评论后按钮是具有“发送评论”类的div。
  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. 问题如下:发送注释的脚本在现有div上的工作原理与charm相似,但是在动态添加的每个div上均无效。 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. 更笼统地说,我找不到在用户操作后添加的div(或任何其他html标记)上执行任何类型脚本的方法。

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. on允许您将处理程序附加到元素,即使DOM中尚不存在处理程序也是如此。 ref: http://api.jquery.com/on/ 参考: http : //api.jquery.com/on/

You might want to replace document from this binding function, it is usually overly broad. 您可能想从此绑定功能替换document ,它通常过于宽泛。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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