开发者

JQuery select based on the FIRST in a string of classes

开发者 https://www.devze.com 2023-01-29 19:57 出处:网络
I\'ve got two elements which are the basis of a small tab script. For various reasons (called Internet Exploder 6) I\'ve had to build it like this:

I've got two elements which are the basis of a small tab script. For various reasons (called Internet Exploder 6) I've had to build it like this:

Tab headers

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

Tab contents

<div class="contents inactive" id="Block1 ">Stuff here</div>
<div class="contents inactive" id="Blo开发者_C百科ck2 ">Stuff here</div>
<div class="contents inactive" id="Block3 ">Stuff here</div>

So when Tab1 is clicked my script needs to get class of "Block1" and then search for the div with the matching class or ID.

But how can I select for the first class in a set of multiple classes? Is there anything along these lines? Is this even possible?

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

Stuck...

Thanks!


I don't think there's any solution that's any prettier than this:

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

... the relative order of the classes are generally not intended to carry any significance, so I don't think there are any helpers for that.


A slightly different way of doing this without having to split or worry about spaces

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

then to grab the correct div to show

var tabtoshow = $(this).children('a').attr('href');


If the headers match the divs in number and order, and they are children of some parent without other siblings, you might be able to make use of the jQuery index method.

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

or

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

(Note that here tabtoshow is a jquery object.)

0

精彩评论

暂无评论...
验证码 换一张
取 消