3

jqueryの.closest()メソッドに問題があります。これは私が問題を抱えている私のhtmlとjqueryの例です。

HTMLERBのスニペット

<% @posts.each do |post| %>
  <tbody>
    <tr>
      <td><%= post.title %></td>
      <td><%= post.description %></td>
      <td><%= post.episodeNum %></td>
      <td><%= post.highDef %></td>
      <td>
        <%= link_to 'Show', post, :class => 'btn btn-info' %>
        <%= link_to 'Edit', edit_post_path(post), :class => 'btn btn-primary' %>
        <%= link_to 'Destroy', post, :class => 'btn btn-danger', confirm: 'Are you sure?', method: :delete %>
      </td>
      <td>
        <b>Votes: </b>
        <p class="current_vote"><font color=#1C1C1C>
          <%= post.upvotes.size - post.downvotes.size %>
        </p></font>
        <button type="button" class="buttonUp btn" id="<%= post.id %>">Increase Vote</button>
        <button type="button" class="buttonDown btn" id="<%= post.id %>">Decrease Vote</button>
      </td>
    </tr>
  <% end %>

JQueryのスニペット

$(document).ready(function() {
    $('.buttonUp').bind('click', function() {
        $.ajax({
            type: "POST",
            url: "/posts/increaseVote?id=" + $(this).attr("id"),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                $(this).closest('p').text(data);
            }
        });
    });
    $('.buttonDown').bind('click', function() {
        $.ajax({
            type: "POST",
            url: "/posts/decreaseVote?id=" + $(this).attr("id"),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                $(this).closest('p').text(data);
            }
        });
    });
});

また、jsonを正しく受信しています。テストの場合、jsonデータのコールバックには整数が含まれているだけです。

4

2 に答える 2

5

pが要素の祖先である場合 は、.closest(); を使用します。

pが要素の兄弟である場合 は、.siblings(); を使用します。

 $(this).closest('p').text(data);

 $(this).siblings('p').text(data);
于 2012-10-08T17:10:03.090 に答える
1

兄弟はいらないの?

 $(this).siblings('p').text(data);

その名前にもかかわらず、closestは自己と祖先を探すために使用され、親要素の子である要素を探しません。

于 2012-10-08T17:08:21.157 に答える