0

我一直在用头撞墙试图让这项工作有一段时间了。我正在尝试将评论正文缩短为一行以进行紧凑的评论预览。我正在使用 jquery .each 函数来遍历我的线程评论系统中的每个 .cbody (评论正文),并将其放在 chead 内的 cshort div 中。它应该可以工作,但我不能在第一行选择 cshort 类。非常感谢任何帮助。据我所见,我的 jquery 应该是这样的:

$('.cbody').each(function(Ind1){
         var str = $(this).text();
         $(this).parent().siblings('.chead').next('.cshort').html(str); 
    });
});

这是评论的html:

<ul>
<li>
<div id="23">
<a name="23">
</a>
<div class="chead">
<a href="#" class="unord">
<img src="images/plus.gif" border="0">
</a>
<a href="userinfo.php?user=muuuuuuuu">
<img src="include/avatar/n.jpg" border="0">
</a>
<span style="display: none;" class="uname">
usersname
</span>
&nbsp;,

<span class="cshort">
</span>
<span class="votes_up" id="votes_up23">
2
</span>
-
<span class="votes_down" id="votes_down23">
0
</span>
<span class="vote_buttons" id="vote_buttons23">
<a href="javascript:;" class="vote_up" id="23">
</a>
<a href="javascript:;" class="vote_down" id="23">
</a>
</span>
</div>
<div class="cbody">
<br>
The comment text funny lol
</div>
<a style="display: none;" href="#" class="reply" id="23">
Reply
</a>
<a style="display: none;" href="#21" class="cparent">
Parent
</a>
</div>
</li>
</ul>
4

3 回答 3

4

cbody 的父母似乎没有兄弟姐妹,所以有点

$(this).parent().siblings('.chead')

没有返回任何东西,你很可能想要

$(this).parent().find('.chead')

或者

$(this).siblings('.chead')

要最直接地访问 cshort,请使用

$(this).parent().find('.cshort')

编辑:

您的 HTML 层次结构如下所示:

ul
| li
| | div#23
| | | a
| | | div.chead
| | | div.cbody
| | | ...
  • $(this)指 cbody
  • $(this).parent()指 div#23
  • $(this).parent().siblings()返回的所有其他子节点li(在您的示例代码的情况下为空)
  • $(this).siblings()指 div.chead 和一些a元素

由于 chead 是 cbody 的兄弟,因此选择它的最佳方法是

$(this).siblings('.chead')
于 2009-03-28T15:38:49.827 回答
1

尝试改变这个:

$(this).parent().siblings('.chead').next('.cshort').html(str);

对此:

$(this).siblings('.chead').children('.cshort').html(str);

.chead并且.cbody是兄弟姐妹,所以你不需要看.cbody' 的父母。此外,.cshort是 的孩子.chead,因此您查看.chead的是 的孩子,而不是其兄弟姐妹(通过.next)。

于 2009-03-28T15:39:00.623 回答
0

不应该追加最后一个方法吗?

.html(str) 每次都会替换它,你只会得到最后一个。

于 2009-03-28T15:40:33.880 回答