如何选择下一个div?

5

我在一个页面中有很多次出现以下这个部分:

<a class="showComment" style="cursor: pointer;"><i class="icon-comment"></i> Views</a>
<br />
<br />
<div class="writeComment" style="height: auto; width: 700px;" dir="ltr" hidden="hidden">
</div>

我现在正在为a.showComment点击事件编写js文件中的代码。现在我想选择下一个div.writeComment,如何选择它?


1
请定义“select”它?比如,你想用它做什么? - PlantTheIdea
2
https://dev59.com/I2HVa4cB1Zd3GeqPl1YM?rq=1 - MC_delta_T
5个回答

3
在变量nextDiv中,您可以随心所欲地进行操作
使用.nextAll()方法允许我们搜索DOM树中这些元素的后继,并从匹配元素构造一个新的jQuery对象。
如果使用.next()代替,则会在单击的DOM元素之后搜索。请尝试以下内容:
 $('.showComment').click(function(){
        var nextDiv = $(this).nextAll("div.writeComment");
    });

或者
$('.showComment').click(function(){
            var nextDiv =  $('.showComment').next().find('.writeComment')
        });

或者

$('.showComment').click(function(){
        var nextDiv = $(this).next("div.writeComment");
    });

3

next()方法无法正常工作。

nextAll()方法是用于选择在我的.showComment元素之后的所有.writeComment元素。但我找到了问题所在。以下代码解决了这个问题。

$('.showComment').click(function(){
     $(this).nextAll(".writeComment").first();
});

2

这可能会通过使用next()方法指向正确的方向,具体信息请参考http://api.jquery.com/next/

选择器将如下所示:

$('.showComment').next('.writeComment')

或者:

$('.showComment').next().find('.writeComment')

@PlantTheIdea 谢谢你的改进 :) 非常感激,干杯! - Matthias Wegtun
没关系,我没做太多哈哈。拼写错误是唯一的真正问题,我只是讨厌在选择器上看到标签限定符,因为这是不必要的,只会使它变得不那么高效。 - PlantTheIdea

-1

我假设你正在使用jQuery。否则,我强烈建议你这样做。 它有一个下一语句

$('#foo').next().css('background-color', 'red');

将 foo 后面的元素背景设置为红色。


-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接