我正在使用jquery nth-of-type
让div上下滑动(slideToggle()
和click()
)。问题是,当我尝试单击其中一个打开选项卡时,它们不会打开。
HTML:
<div id="tabs-wrapper">
<div class="op">Tab One</div>
<div class="op">Tab Two</div>
<div class="op">Tab Three</div>
<div class="tab">Pattern One</div>
<div class="tab">Pattern One</div>
<div class="tab">Pattern One</div>
</div>
JS:
$('.tab').hide();
$('.op:nth-of-type(1)').click(function(){
$('.tab:nth-of-type(1)').slideToggle();
});
$('.op:nth-of-type(2)').click(function(){
$('.tab:nth-of-type(2)').slideToggle();
});
$('.op:nth-of-type(3)').click(function(){
$('.tab:nth-of-type(3)').slideToggle();
});
答案 0 :(得分:3)
:nth-of-type()
伪类只关注元素类型。没有你的&#34;标签&#34;元素是其容器中的第一个,第二个或第三个<div>
,因此没有匹配选择器。
我认为你可以这样做:
$('.op:nth-of-type(3n+1)').click(function(){
$('.tab:nth-of-type(3n+1)').slideToggle();
});
当您添加/删除标签时,您必须确保3
已更新。
或者你可以这样做:
$(".op").click(function() {
$(".tab").eq($(this).index()).slideToggle();
});
然后你只需要设置一个处理程序。
答案 1 :(得分:1)
用一个例子来完成Pointy的回答:
$('.tab').hide();
$('.op:nth-of-type(1)').click(function(){
$('div:nth-of-type(4)').slideToggle();
});
$('.op:nth-of-type(2)').click(function(){
$('div:nth-of-type(5)').slideToggle();
});
$('.op:nth-of-type(3)').click(function(){
$('div:nth-of-type(6)').slideToggle();
});
答案 2 :(得分:1)
您也可以使用:eq
选择器。然后元素将按预期计数,0-2(从0开始索引)。
$('.tab').hide();
$('.op:eq(0)').click(function(){
$('.tab:eq(0)').slideToggle();
});
$('.op:eq(1)').click(function(){
$('.tab:eq(1)').slideToggle();
});
$('.op:eq(2)').click(function(){
$('.tab:eq(2)').slideToggle();
});
http://jsfiddle.net/rm9mkoau/6/
或者很快,不依赖于元素编号。
$('.tab').hide();
$('.op').click(function(){
$('.tab:eq(' + $(this).index() + ')').slideToggle();
});
答案 3 :(得分:1)
您可以在尖锐的答案中得到解释,但是到目前为止为解决方案添加一些变化,您可以尝试这种方法:
$('.op').click(function() {
var pos = $(this).parent().indexOf($(this));
$('.tab').eq(pos).slideToggle();
});
这可以是浓缩的,但我已经把它留在了一个更易读的形式,这样你就能掌握它所做的事情。
它说&#39;:&#34;让我知道这个被点击的&#39; op&#39;元素在其父元素中的所有其他元素中。获取所有&#39;标签&#39;元素和slideToggle对应于&#39; op&#39;的位置的tab元素。点击了元素。&#34;
注意:这会定位您标记中的所有.op
和.tab
元素,您可以选择使其更具体。
答案 4 :(得分:1)
nth-of-type
选择器仅基于元素名称进行区分 - 而不是类。
:nth-of-type(an + b)伪类表示法表示一个元素 它有一个+ b-1兄弟姐妹,前面有相同的扩展元素名称 在文档树中,对于n的任何零或正整数值,和 有一个父元素。 http://www.w3.org/TR/css3-selectors/#nth-of-type-pseudo
此处的一种替代方法是使用jQuery :eq
selector
$('.tab').hide();
$('.op:eq(0)').click(function(){
$('.tab:eq(0)').slideToggle();
});
$('.op:eq(1)').click(function(){
$('.tab:eq(1)').slideToggle();
});
$('.op:eq(2)').click(function(){
$('.tab:eq(2)').slideToggle();
});
虽然更优雅的解决方案是使用jQuery.index
选择与所点击的.tab
具有相同索引的.op
。
$('#tabs-wrapper').on('click', '.op', function(){
var $t = $(this), $tab;
$tab = $t.siblings('.tab').eq($t.index());
$tab.slideToggle();
});