How do I use part of a class as variable using jQuery
I've got an element like this:
<ul class="MainMenu_SubMenu m m0 mid157">
I need to get the mid157 and use that 157 for a variable for something开发者_如何学运维 else, i.e:
$('SomeOtherElement157')
So my question is how do get the class name as a variable and then strip all but the number? The classes are generated so some have more and some have less but they will all have that mid...
var className = $('ul').attr('class'),
midNum = /\bmid(\S+)/.exec(className)[1],
selector = 'SomeOtherElement' + midNum;
$(selector);
Works for all of the following:
<ul class="MainMenu_SubMenu m m0 mid157"></ul>
<ul class="mid158"></ul>
<ul class="mid159 MainMenu_SubMenu m m0"></ul>
<ul class="MainMenu_SubMenu mid160 m m0"></ul>
Demo: http://jsfiddle.net/mattball/P3G8H/
You can use grep:
var classes=$("div").attr("class").split(" ");
var matches = jQuery.grep(classes, function(n, i){
return n.indexOf("mid")===0;
});
if(matches[0]){
var number=matches[0].substring(3);
// do something with that number
}
var patt1 = /mid(\d+)/,
matches = $('ul').attr('class').match(patt1);
if (matches != undefined && matches[1] != undefined) {
$('SomeOtherElement'+matches[1]);
} else {
alert("No matches.");
}
var id = $("div").attr("class").match(/mid([\d]+)/gi)[0].replace("mid", "SomethingElse");
alert(id);
http://jsfiddle.net/bkSFf/
var nums =
document.getElementsByTagName('ul')[0]
.className.match(/.*mid(\d*)/)[1];
$('selector' + nums);
精彩评论