我在一个页面中多次使用此部分:
<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>
我现在正在js文件中为a.showComment
点击事件编写代码。现在我想选择下一个div.writeComment
。如何选择它?
答案 0 :(得分: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");
});
答案 1 :(得分:3)
next()没有用。
nextAll()适用于我的.showComment元素之后的所有.writeComment元素。但我发现了这个问题。以下代码实现了它。
$('.showComment').click(function(){
$(this).nextAll(".writeComment").first();
});
答案 2 :(得分:2)
这可能会使用next()http://api.jquery.com/next/以正确的方式显示 选择器如下:
这样:
$('.showComment').next('.writeComment')
或:
$('.showComment').next().find('.writeComment')
答案 3 :(得分:-1)
我假设你使用jQuery。否则,我强烈建议你这样做。 它有一个next-statement:
$('#foo').next().css('background-color', 'red');
在背景后设置元素:红色。
答案 4 :(得分:-1)
使用~
选择器。 JQuery Reference
$('a.showComment ~ div.writeComment')