【问题标题】:selecting parent blocks with jquery使用 jquery 选择父块
【发布时间】:2012-03-30 01:04:50
【问题描述】:

我有以下标记:

<tr>
<td class="message">
    <p>This is a test post</p>
</td>
<td class="metadata">
    <div class="top">
        <a href="">#1</a><br/>
        <span>12.03.2012</span><br/>
    </div>
    <div class="bottom">
         <a href="" class="light-button quote">Quote</a>
    </div>
</td>
</tr>

我在一个页面上有多个帖子,我想用 js 实现引用帖子。当用户单击引用按钮时,它应该采用段落文本 到目前为止我尝试了什么:

$('a.quote').on('click', function(e){
    e.preventDefault();

    $(this).closest('.message > p').text();      
});`

但这不起作用。它返回一个空字符串。

编辑:我让它工作了 $(this).closest('td').prev().children('p.thread-message').html();

【问题讨论】:

  • 对于初学者,您不是在寻找父块,而是在寻找兄弟 td

标签: jquery dom jquery-selectors


【解决方案1】:

这会起作用的;

var quote = $(this).parents('tr').first().find('.message p').text();

demo

【讨论】:

    【解决方案2】:

    $(this).parents('td').siblings('.message').children('p').text()

    您需要像@Shyju 的帖子一样一直到父 TR,或者去父 TD 并抓住它的兄弟。

    【讨论】:

      【解决方案3】:

      这对我有用。

      $('a.quote').on('click', function(e){
          e.preventDefault();
           alert($(this).closest('td').prev('td').find('p').html());      
      });
      

      ​ 这是 jsfiddle 示例:http://jsfiddle.net/7tfMK/9/

      【讨论】:

      • 我的页面上有多个帖子,我需要获取相对于引用按钮的 p,否则我会得到奇怪的数据
      • @Mythriel:使用一些 div 代替 td / tr 并将相关数据分组。
      【解决方案4】:

      我会这样做

      $('.message > p', $(this)).text();      
      

      这是未经测试的,可能不需要将 this 包装到 jQuery 对象中。

      【讨论】:

      • 这相当于$(this).find('.message &gt; p'),但.message &gt; p不是按钮的子元素。
      猜你喜欢
      • 2016-03-12
      • 2011-03-01
      • 2011-03-21
      • 2011-04-19
      • 2023-04-04
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多