Given this HTML:
<div id="foo">
<input type=button class="foo abtn_1">
<input type=button class="joe bbtn_2">
<input type=button class="doe cbtn_2">
<input type=button class="cool dbtn_1">
</div>
When I click a button, I need to get the class of which contains the underscore (only) and change its number from 2 to 1.
Currently I use this for each class:
$('.abtn_1').live('click', function () {
$(this).switchClass('abtn_1','abtn_2');
});
$('.abtn_2').live('click', function () {
$(this).switchClass('abtn_2','abtn_1');
});
$('.bbtn_1').live('click', function () {
$(this).switchClass('bbtn_1','bbtn_2');
});
$('.bbtn_2').live('click', function () {
$(this).switchClass('bbtn_2','bbtn_1');
});
// etc
So instead of having this so many times I thought of turning the whole thing in a line or two by getting the underscore class and change its number accordingly of what number it is.
I would imagine it would go something like:
var a = // $(this).attr('class') without number and underscore
var b = // This class number only
var c = $(this).attr('class'); // If I wanted to call it from
// its parent $('#foo input').
if a contains number 1 {
$(this).switchClass(c, a + '_1')
} else {
$(this).switchClass(c, a + '_2')
};
This code will do the following:
.live()with.delegate()(since OP using jQuery 1.6)aaa_1orbbb_2class name no matter where it is in the class name listHere’s the code:
When using
.delegate()or.on(), you should pick a static parent element for the main jQuery object selector. I useddocumenthere only because you didn’t disclose the rest of your HTML, but it’s better to use something closer to the actual target elements.Here’s another interesting way to do it using a custom replace function:
Demo here: http://jsfiddle.net/jfriend00/xgUzT/