First of all the fiddle: http://jsfiddle.net/6d82Q/1/
In my HTML I have:
<div class="myClass" data-status="true"></div>
<div class="myClass" data-status="false"></div>
I want to add a CSS-class to a div depending on the status:
$('.myClass').each(function()
{
// compare status
if($(this).data('status') == 'true')
{
$(this).addClass('myTrueClass');
}
else
{
$(this).addClass('myFalseClass');
}
});
The Problem is, that always myFalseClass
is added. My question is: How can the problem be fixed and why does it occur in the first place?
The .data()
method will perform some auto-casting on [data-*]
attributes, which makes passing data to the client very convenient.
As you're storing what would be auto-cast to a boolean, you can use:
if ($(this).data('status')) {
...
} else {
...
}
If you need to make sure that the value is true
, and not just truthy (like a value of 1
) then be sure to use a reference comparison:
if ($(this).data('status') === true) {
...
} else {
...
}
As an aside, there's no reason to call .each()
when you could simply pass a function to .addClass()
:
$('.myClass').addClass(function () {
return $(this).data('status') ? 'myTrueClass' : 'myFalseClass';
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments