<div class="nav-top">
<ul>
<li class="test tab1"><a href="/">test</a></li>
<li class="tes tab2"><a href="#">test</a></li>
<li class="tes tab3"><a href="#">test</a></li>
<li class="navahead"><a href="#">test</a></li>
<li class="navahead"><a href="#">test</a></li>
<li class="new"><a href="#">test</a></li>
</ul>
</div>
<div id="subnav-content" class="tab1">hello world</div>
supposed a variable like the following:
var tab_class = $(this).attr('class'); //this equals li
i want to use tab1 tab2 tab3 independently in the following code eg:
$("#subnav-content div." + tab_class).show();
the tab_class
will get two value(test tab1). how to get rid of the test and the 开发者_开发技巧space?
tab_class.split(/\s+/).pop()
To get the last class.
EDIT: But, as Tarun kindly pointed out, classes may be rearranged in alphabetical order while rendering. So my vote goes for Shef's answer, but you need to check if there are any matches before dealing with it as with array.
tabs = tab_class.match(/(tab\d+)/g);
tab_class = (tabs) ? tabs[0] : 'none';
Updated the code to account for @Hnatt's suggestion.
With this code, if the variable tab_class
contains a class name such as tab1
, tab2
, ... it will be assigned that name, otherwise it will be assigned none
.
Test case
Instead of getting rid of the test
and the space, focus on getting the tab1
out of that variable.
In addition, this is not correct:
$("#subnav-content div." + tab_class).show();
It should be
$("div#subnav-content." + tab_class).show();
var tab_class = $(this).attr('class').split(' ')[1]
but its probably bad idea to hard code index ;]
just a suggestion, why dont u write your code as:
<div class="nav-top">
<ul>
<li class="test tab1" id="tab1-link"><a href="/">test</a></li>
<li class="tes tab2" id="tab2-link"><a href="#">test</a></li>
<li class="tes tab3" id="tab3-link"><a href="#">test</a></li>
<li class="navahead" id="tab4-link"><a href="#">test</a></li>
<li class="navahead" id="tab5-link"><a href="#">test</a></li>
<li class="new" id="tabx-link"><a href="#">test</a></li>
</ul>
</div>
<div id="subnav-content" class="tab1">hello world</div>
and then use following js:
...
var tab_class = $(this).attr('id');
tab_class = tab_class.replace('-link','');
...
the advantage here is that there wont be any JS error. performance wont suffer as we are only assigning ID to DOM elements.
You could do:
tab_class = tab_class.replace('tes ','');
精彩评论