【问题标题】:Grab content of closest previous div抓取最近的前一个 div 的内容
【发布时间】:2015-07-01 10:26:59
【问题描述】:

我目前正在做一些事情,可以称为回复某人在某种文章下的帖子。

基本上,我想要实现的是当您单击帖子下方的“回复帖子”(.comment-reply 类)时 - 您从 .comment-username div 中获取其作者姓名并将其放入 textarea .问题是定位这个 div 并获取我想要放入变量并稍后放入 textarea 的内容。无法确定这种瞄准和抓取。入口的基本结构是这样的:

<div class="comment-block comment-child">
    <div class="comment-info title-small text-bold">
        <div class="push-left">
            <span class="comment-username sm-fc">AUTHOR NAME is here</span>
            <span class="comment-time">some date</span>
        </div>
        <div class="push-right">
            <span class="comment-rating">some int value</span>
        </div>
        <div class="clear"></div>

    </div>
    <div class="comment-text">
        Sample text => Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
    <div class="comment-functions">
        <span class="comment-reply title-small text-bold">reply to post</span>
        <span class="comment-rate comment-plus"> + </span>
        <span class="comment-rate comment-minus"> - </span>
    </div>  
</div>

此外,在同一页面上会显示很多帖子,所以我不想为每个帖子都使用 ID,而是使用在这种情况下对我来说更清楚的类。

我一直在尝试$.prev()、$.closest(),但没有结果。

有什么建议吗?

【问题讨论】:

  • 你试过 prevAll( ) 吗?
  • 是的,一直在尝试关注这个:stackoverflow.com/questions/2310270/… 但没有结果
  • 您是针对 div 来获取 id 还是 span?
  • Rory McCrossan 提交了一个非常好的方法,谢谢大家

标签: javascript jquery html css


【解决方案1】:

您可以使用closest() 来获取通用.comment-block 容器,然后从那里find() .comment-username 并检索text()。试试这个:

$('.comment-reply').click(function() {
    var username = $(this).closest('.comment-block').find('.comment-username').text();
    // do something with the username here...
});

Example fiddle

【讨论】:

  • 完美运行,不敢相信它真的那么简单。非常感谢。
  • 没问题,很乐意提供帮助。
【解决方案2】:

有了父母(选择器),您可以:

 var name = $(this).parents('.comment-username').text();

祝你好运。

【讨论】:

  • 请注意 .comment-username 不是 .comment-reply 的父级 - 所以这不会找到用户名值。
  • 这是真的,抱歉没有正确阅读。在另一种情况下,这非常有效。
猜你喜欢
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 2023-03-03
相关资源
最近更新 更多