jQuery submit()只发生一次,应该发生更多

时间:2012-04-15 11:40:23

标签: jquery ruby-on-rails

我想在帖子中添加评论功能。 我可以添加注释一次,部分渲染没有重新加载,但是当我添加另一个注释时它只渲染部分(没有别的) 这是我正在调用的create方法:

  def create
    @comment = Comment.new(params[:comment])
    @snippet = @comment.snippet
    @comment.save
    @comment = Comment.new
    render :partial => "snippets/comment"
  end

使用Javascript:

$(document).ready( function(){
    save_comment();
});
function save_comment() {
    $("#new_comment").submit(function (e) {
        e.preventDefault();
        var url = "/comments/create";
        var post_data = $('#new_comment').serialize();
        logger(post_data);
        post_data = add_auth_token(post_data); // add authenticity token to post for forgery protection (works fine)
        $.post(url,
            post_data,
            function(data) {
                $("#comments_container").html(data);
                $("#comment_value").val("");
            });
    });
}

表格

<%= form_for(@comment) do |f| %>
  <%= f.text_field :value %>
  <%= f.hidden_field :user_id, :value => current_user.id %>
  <%= f.hidden_field :snippet_id, :value => @snippet.id %>
  <div class="actions">
    <%= f.submit "Post" %>
  </div>
<% end %>

1 个答案:

答案 0 :(得分:1)

由于在执行事件侦听器代码之后添加了html,因此无法为稍后在DOM中添加的元素附加submit的事件处理程序。您需要使用on api来绑定事件,它将附加一个委托事件处理程序,该事件处理程序可以处理来自稍后添加到文档的后代元素的事件。

在您的情况下,您需要将代码更改为:

$(document).ready( function(){
    save_comment();
});
function save_comment() {
    $(document).on("submit","#new_comment",function (e) {
        e.preventDefault();
        var url = "/comments/create";
        var post_data = $('#new_comment').serialize();
        logger(post_data);
        post_data = add_auth_token(post_data); // add authenticity token to post for forgery protection (works fine)
        $.post(url,
            post_data,
            function(data) {
                $("#comments_container").html(data);
                $("#comment_value").val("");
            });
    });
}