2010-12-07 46 views
1

我有两个元素,这是一个小标签脚本的基础。由于各种原因(称为Internet爆6)我不得不建立这样的:JQuery基于类的字符串中的第一个选择

标签头

<span class="Block1 inactive" id="Tab1">Label1</span> 
<span class="Block2 inactive" id="Tab2">Label2</span> 
<span class="Block3 inactive" id="Tab3">Label3</span> 

标签内容

<div class="contents inactive" id="Block1 ">Stuff here</div> 
<div class="contents inactive" id="Block2 ">Stuff here</div> 
<div class="contents inactive" id="Block3 ">Stuff here</div> 

所以被点击时TAB1我的脚本需要获得“Block1”类,然后使用匹配的类或ID搜索div。

但是我怎样才能选择一组多个类中的第一个类?这有什么意义吗?这甚至有可能吗?

var tabtoshow = $(this).attr('class':first); 
var tabtoshow = $(this).attr('class:first'); 
var tabtoshow = $(this).attr('class[0]'); 

卡住...

谢谢!

回答

3

我不认为有这么比这更漂亮的任何任何解决方案:

var tabtoshow = $(this).attr('class').split(' ')[0]; 

...类的相对顺序一般不打算进行任何的意义,所以我不认为有是任何帮助者。

+0

我建议.split(/ \ s + /)来排序有多个空间的问题 – 2010-12-07 11:31:24

+0

@Jon:在寻找第一类时并没有影响任何东西,但是确实如此。 – 2010-12-07 11:48:06

0

如果标题在数量和顺序上与div匹配,并且它们是没有其他兄弟的父母的孩子,那么您可以使用jQuery index方法。

var tabtoshow = $('.contents').eq($(this).index()); 

var tabtoshow = $('#Block' + ($(this).index() + 1)); 

(注意,这里tabtoshow是一个jQuery对象。)

1

一个这样做的方式略有不同,而无需拆分,也不用担心空间

<span class="inactive" id="Tab1"><a href="#Block1">Label1</a></span> 

然后抓住正确的div来显示

var tabtoshow = $(this).children('a').attr('href'); 
相关问题