【问题标题】:How to Access Closest p tag in jquery?如何在 jquery 中访问最近的 p 标签?
【发布时间】:2012-09-28 23:19:09
【问题描述】:

我在使用 jquery 中的 .closest() 方法时遇到问题。这是我遇到问题的 html 和 jquery 示例。

HTML ERB 片段

<% @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 数据回调只包含一个整数。

【问题讨论】:

    标签: jquery html ruby-on-rails ajax


    【解决方案1】:

    如果 p 是元素的祖先,则使用 .closest();

    如果 p 是元素的兄弟,使用 .siblings();

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

    【讨论】:

    • 兄弟只有一个'b',就像我告诉dystroy一样
    【解决方案2】:

    你不需要siblings 吗?

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

    尽管有它的名字,closest 用于查找自身和祖先,而不是查找作为父元素的子元素的元素。

    【讨论】:

    • @TheZ 谢谢。当英语是一门外语时,这不是一个常用词:)
    猜你喜欢
    • 1970-01-01
    • 2017-08-02
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2018-04-02
    • 2021-01-22
    • 1970-01-01
    相关资源
    最近更新 更多