javascript - jquery 如何给帖子添加评论

标签 javascript jquery

您好,我目前正在制作一个“论坛”,用户可以在其中提交帖子并将其显示出来。我想要添加评论的选项。

我正在做客户端的所有事情。

下面是生成论坛的代码:

$.get(url, page, function(data){
      $("#forum").html("");
      for(var i in data)
      {
        $("#forum").append(buildForumEntry(data[i]));
      }
    });

// Builds the forum entry
  function buildForumEntry(post)
  {
    var titleAndType = '<div><span class="forum-title">'+post.title+'</span>'+buildType(post.type)+'</div>';
    var author =  "<div class=\"forum-author\">By: "+post.author+" on "+formatDate(post.date)+"</div>";
    var body =    "<pre>"+post.body+"</pre>";
    var comment = "<div class=\"forum-comment\"> <div class=\"btn-group\"><a class=\"btn btn-mini btn-primary\" role=\"button\" data-toggle=\"modal\" id=\"btn-forum-comment\"><i class=\"icon-comment icon-white\"></i> comment</a></div></div>";
    var footer =  "<hr style=\"border-top: 1px dotted #b0b0b0;border-bottom: 0px\">";
    var entry = titleAndType+author+body+comment+footer;
    return entry;
  }

当我点击评论按钮时,我该怎么做才能获取帖子的一些信息?同样在此方法中调用:

// Button comment
  $("#btn-forum-comment").click(function() {
    alert("clicked");
  });

这不会起作用,因为有超过 1 种类型的“id=btn-forum-comment”。我应该上课吗?如果是这样,我如何获取更多实例的帖子标题,以便在我发布到我的服务器时我可以更新正确的条目。

更新:类在生成的论坛中不起作用。按钮点击没有被触发。有什么想法吗?

var comment = '<div class="btn-group"><a class="btn btn-mini btn-primary btn-forum-comment" id="btn-forum-comment-'+post._id+'"><i class="icon-comment icon-white"></i> comment</a></div>';

// Button comment
  $(".btn-forum-comment").click(function() {
    // now you know the id of clicked comment, so you can rewrite this with code which will open a form to answer exactly this comment
    console.log("clicked");
    alert($(this).attr('id')+" clicked"); 
  });

我在点击时遇到问题,我认为这与动态加载有关。我将该类应用于硬编码的 html 并且它有效。但不是动态的感谢。

UPDATE2:为 future 的用户更新。我需要使用委托(delegate)函数

$("#forum").delegate(".btn-forum-comment", "click", function() {
    console.log("clicked");
    alert($(this).attr('id')+" clicked");     
  });

最佳答案

为您的按钮添加一个类:

<a class=\"btn btn-mini btn-primary btn-forum-comment\" ... id=\"btn-forum-comment-"+post.id+"\">

还有一个类(class)

  var entry = "<div class='post'>"+ titleAndType+author+body+comment+footer +  "</div>"; 

您的事件处理程序:

$(".btn-forum-comment").click(function() {
    var post = $(this).parents(".post"); //the post of this clicked button
    //from there you can access title, author,... of this post.
    var title = post.find(".forum-title");
  });

通过这种方法,您将能够访问所单击按钮的正确标题、作者等。

关于javascript - jquery 如何给帖子添加评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17386420/

相关文章:

javascript - Facebook 点赞按钮无法加载(宽度为 0)

javascript - 登录google plus api后如何获取用户数据?

javascript - Datetimepicker 不使用给定的格式

jquery - 将内容添加到动态 fancybox

javascript - MathJax 与 MathJax.Hub.Queue 和 Typeset 的问题

javascript - 在d3js中的svg圆圈内添加svg文本

javascript - 如果所选日期是数组数组中的最后一个日期,则返回 false

javascript - Masonry JS 边距问题

javascript - 点击删除用JS制作的动态div

jquery:向新创建的元素添加事件