【问题标题】:Problem selecting class using jquery使用 jquery 选择类的问题
【发布时间】:2010-10-16 03:08:19
【问题描述】:

一段时间以来,我一直在用头撞墙来尝试完成这项工作。我正在尝试将评论正文缩短为一行以进行紧凑的评论预览。我正在使用 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>

【问题讨论】:

    标签: jquery multithreading comments css-selectors each


    【解决方案1】:

    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')
    

    【讨论】:

    • 非常感谢,已经整理好了。你能解释为什么 cbody 父 div 没有兄弟姐妹吗? chead不是兄弟姐妹吗?
    【解决方案2】:

    尝试改变这个:

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

    到这里:

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

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

    【讨论】:

    • 谢谢,你的方法也很有效,我给了 cobbal 正确的答案,因为他的速度快了一点,不过还是支持你。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-03-20
      • 2020-10-07
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      相关资源
      最近更新 更多