JQuery if/else statement matching a wildcard CSS name
I am trying to write an if else
statement in JQuery, which can change an element's class by matching 'IN'
or 'OUT'
.
For example: I have several <DIV>
tags that each have class='IN-something'
or class='OUT-something'
.
The below would work if I knew the exact CSS class, b开发者_运维百科ut all I'll know is that it contains 'IN' or 'OUT'.
So something like this:
if ($(jRow).hasClass('IN-*')){
jRow.attr( "class", "OUT-foo" );
}else{
jRow.attr( "class", "IN-foo");
}
Does anyone have any helpful ideas?
if ($(jRow).attr('class').indexOf('IN-') !== 1)
{jRow.attr( "class", "OUT-foo" );}
else
{jRow.attr( "class", "IN-foo");}
You can use the attribute-contains-prefix-selector
(docs) if that will be the entire class value (or at least that is the first class).
if ($(jRow).is('[class |= IN]')) {
This also uses the is()
(docs) method to see if jRow
is a match.
Click here to test a working example. (jsFiddle)
EDIT:
If your point was that you won't know what foo
is, and you need to retain it, I'd do something like this instead:
jRow.attr('class', function(i,cls) {
return cls.indexOf('IN') > -1 ? cls.replace('IN','OUT') : cls.replace('OUT','IN');
});
You can pass a function as the second argument to the attr()
(docs) method. That function has 2 parameters. The first is the current index in the iteration. The second is the current value of the attribute.
The return value is the value that will be set.
Use jQuery data to store "IN" or "OUT", or add an attribute of your own with a business-logic-appropriate name that says "IN" or "OUT". The real problem here is combining classnames.
You could also break out the IN
and OUT
and use multiple classes.
<tr class = "IN foo"/>
if( $obj.hasClass("in") ){ $obj.removeClass("in").addClass("out") }
var class = $(jRow).attr('class');
if (class.search("IN\-.*")) {
jRow.attr( "class", "OUT-foo" );
}
else {
jRow.attr( "class", "IN-foo");
}
精彩评论