0

所以我有一个动态插入的评论表单,在提交表单后,我将它与服务器 ajax,并将评论附加到评论部分,但附加部分不起作用。这就是我所拥有的:

$(".action-link-comment").click(function() {
  if ($(this).parent().parent().find('.comment-form')[0]){
    return false;
  }
  $(this).parent().parent().append('<div class="comment-form"><form class="comment-input"><input class="input-xlarge comment-val" type="text" placeholder="Write a comment..." style="height:14px;"/><input type="submit" style="position:absolute;left:-9999px;width:1px;height:1px;"/></form></div>');
  $(".comment-input").submit(function(event) {
    event.preventDefault();
    var comment = $(this).find('.comment-val').val();
    var post_id = $(this).parent().parent().find('.post-id').html();
    $.ajax({
      url:'/comment',
      type: 'POST',
      dataType: 'json',
      data : {'p' : post_id,
        'data' : comment},
        success: function(response, textStatus, jqXHR) {
          $(this).parent().parent().siblings('.comments-container').append('<div class="comment"><label class="hover><a href="/user/' + response.userid + '"><strong>' + response.name + '</strong><' + '/a><' + '/label><span class="displaynone comment-id">' + response.comment_id + '</span><span class="comment-content">' + response.data + '</span><div class="comment-actions"><a href="javascript:void(0)" class="c-action"><i class="icon-thumbs-up"></i>Like</a><a href="javascript:void(0)" class="c-action"><i class="icon-thumbs-down"></i>Dislike</a><a href="javascript:void(0)" class="c-action reply"><i class="icon-pencil"></i>Reply</a></div>');
        },
    });

  });
});

对于 HTML:

<div class="post-container">
    ...
    <div class="post-actions">
        <span class="p-action comment">
            <a class="action-link-comment" href="javascript:void(0)">Comment</a>
        </span>
    </div>
</div>
4

2 回答 2

4

您应该缓存您的this对象,在success函数的上下文中this不引用您想要的对象。

$(".action-link-comment").click(function() {
         var $this = $(this);       
         //....  
         success: function(response, textStatus, jqXHR) {
              $this.parent().parent()
         // ...
});
于 2012-08-22T01:22:42.067 回答
4

this里面使用success的时候,指代.comment-input。在进行ajax调用之前存储参考:

$(".action-link-comment").click(function() {
    var self = this;
    // ...
    $.ajax({
     // ...
     success: function(response, textStatus, jqXHR) {
       $(self).parent().parent()...
     }
    });
});
于 2012-08-22T01:22:51.923 回答