【问题标题】:How can i run jQuery on content added dynamically?如何在动态添加的内容上运行 jQuery?
【发布时间】:2013-11-23 19:37:27
【问题描述】:

我制作了一个非常类似于 Facebook 墙页的页面:有一些帖子,每个帖子都有一个 cmets 列表,每个帖子都有一个“发送”按钮,用于发送新评论。

在以下示例中:

  1. 帖子使用“mypost”类标识。
  2. post-new-comment 按钮是具有“send-comment”类的 div。
  3. 滚动到底部后,更多帖子会使用我未在此处编写的脚本动态加载。
  4. 当您点击“send-comment”时,会调用一个脚本并且 评论已添加到数据库中。

这是页面的一部分。

<!--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>

当用户向下滚动页面时,其他帖子被注入页面,结果如下:

<!--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>

问题如下:发送 cmets 的脚本在现有 div 上运行起来很像魅力,但在每个动态添加的 div 上,没有任何效果。未检测到点击。什么都没有发生。

更一般地说,我无法找到一种方法使任何类型的脚本在用户操作后添加的 div(或任何其他 html 标记)上工作。

有人可以提出解决此问题的解决方案吗?

【问题讨论】:

标签: javascript jquery html ajax


【解决方案1】:

试试这个:

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

on 允许您将处理程序附加到元素,即使它们尚不存在于 DOM 中。参考:http://api.jquery.com/on/

您可能希望从此绑定函数中替换 document,它通常过于宽泛。

【讨论】:

  • 我认为$('body') 在你不知道父容器的情况下会是一个更合适的选择器。
  • 是的,只要 A) 延迟执行并且 B) HTML 文档有效并且存在 body 元素 - 并且每个人都验证他们的 HTML,对吗? :) 我看到很多使用 document 的示例,因为根据文档:“在加载任何其他 HTML 之前,文档元素在文档头部可用,因此在此处附加事件是安全的,无需等待文件准备好了。”
  • 从我上面看到的最近的父母是.mypost 所以&lt;script&gt; $('.mypost').on('click', '.send-comment', function() { //send comment }); &lt;/script&gt;
  • 理想情况下,您希望为绑定事件的所有元素找到一个共同的祖先。 document 当然不理想,但也不是使用多个绑定上下文。无论#div1#div2#div3 的父元素是什么元素都是理想的候选者,但该元素并未显示。
  • 帖子 div 位于“content-div”内,该“content-div”位于“center-column-div”内,“center-column-div”位于 内的“包装器”内。所有这些 div 始终存在并与页面一起加载。那么,绑定 .on 函数的最佳候选者是什么?仍然是文档还是“content-div”?有什么区别?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多