【问题标题】:Javascript function doesn't work after adding content dynamically through ajax通过ajax动态添加内容后Javascript功能不起作用
【发布时间】:2017-03-09 13:33:35
【问题描述】:

我有一个函数

function reply(id) {
        $('#reply_'+id).toggle();
        return false;
    }

和Ajax函数

<script type="text/javascript">
function post()
{
  var comment = document.getElementById("comment").value;
  var course_id = document.getElementById("course_id").value;
  var user_id = document.getElementById("user_id").value;
  if(comment)
  {
    $.ajax
    ({
      type: 'post',
      url: 'comments.php',
      data: 
      {
         comment:comment,
         course_id:course_id,
         user_id:user_id
      },
      success: function (response) 
      {
        document.getElementById("comment-list").innerHTML=response+document.getElementById("comment-list").innerHTML;
        document.getElementById("comment").value="";

      }
    });
  }

  return false;
}
</script>

以及ajax调用后添加的内容

...
...
 <p class="text-right"><a href="#" onclick="return reply(<?php echo $i; ?>);" class="btn btn-default btn-sm"><i class="fa fa-reply"></i> reply</a></p>    
...
...
<div class="row" id="reply_<?php echo $i; ?>" style="display: none;">
...
...

所以基本上javascript函数切换div并且它在页面刷新时工作得很好但是当通过ajax成功调用添加时javascript切换不起作用。它会在我刷新页面后工作.

无论如何要解决这个问题,所以当通过 ajax 添加内容而不刷新时切换工作。

谢谢。

【问题讨论】:

  • 检查每个元素应该唯一的 id。
  • 他们是。就像我说的。它在页面刷新时有效,但在通过 ajax 添加时无效

标签: javascript jquery ajax


【解决方案1】:

更改 ajax 调用后添加的内容如下:

<p class="text-right">
<a href="#" data-id="<?php echo $i; ?>" class="btn btn-default btn-sm btnReply">
<i class="fa fa-reply"></i> reply</a></p> 

并编写如下的jquery代码

$("body").on("click", ".btnReply", function(event){
   var id =$(this).attr('data-id');
   reply(id);
});   

【讨论】:

  • OK 切换有效,但问题是现在当我单击按钮时,它会转到页面顶部,我必须向下滚动才能看到。之前页面停留在原来的位置。
  • &lt;script type="text/javascript"&gt; $("body").on("click", ".btnReply", function(event){ var id =$(this).attr('data-id'); reply(id); }); function reply(id) { $('#reply_'+id).toggle(); return false; } &lt;/script&gt;
猜你喜欢
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-04-18
相关资源
最近更新 更多