I want to addClass
to element if value
less than zero, value is negative number -0.3
, but what i tried so far not working.
var rate = $('#view-ad-rating');
var text = parseInt($(rate).text());
if (text < 0) {
$(rate).addClass('viewAdRateBad');
} else {
//$(rate).addClass('viewAdRateGood');
}
.viewAdRateBad {
color: red;
}
.viewAdRateGood {
color: green;
}
<script src=".1.1/jquery.min.js"></script>
<a id="view-ad-rating">-0.3</a>
I want to addClass
to element if value
less than zero, value is negative number -0.3
, but what i tried so far not working.
var rate = $('#view-ad-rating');
var text = parseInt($(rate).text());
if (text < 0) {
$(rate).addClass('viewAdRateBad');
} else {
//$(rate).addClass('viewAdRateGood');
}
.viewAdRateBad {
color: red;
}
.viewAdRateGood {
color: green;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="view-ad-rating">-0.3</a>
I also tried this but no success:
if (text <= -1) {
How can solve this?
Share Improve this question asked Jan 10, 2018 at 16:13 Jack The BakerJack The Baker 1,9033 gold badges27 silver badges64 bronze badges 18-
5
Try
parseFloat()
instead ofparseInt()
. The "Int" means "integer". – Pointy Commented Jan 10, 2018 at 16:14 -
@Pointy But the number can be positive, like
11
or65
, no problem? – Jack The Baker Commented Jan 10, 2018 at 16:15 -
FYI an
int
is a whole number, so when you try to parse-0.3
it is rounding to0
. – Jim Wright Commented Jan 10, 2018 at 16:15 - 5 Why would you name a number 'text'? – Jared Smith Commented Jan 10, 2018 at 16:17
- 1 @tourtravel what JaredSmith try to say to you, is that your variable name is not really the best one. You can use text() to retrieve it, but for exemple, it would be better if your variable "text" was named "adRatingValue" for example. – MathKimRobin Commented Jan 10, 2018 at 16:22
1 Answer
Reset to default 8Use parseFloat
instead of parseInt
because parseInt
just parses the first part as 0
and it is not negative. Working code:
var rate = $('#view-ad-rating');
var text = parseFloat($(rate).text()); // <- HERE
if (text < 0) {
$(rate).addClass('viewAdRateBad');
} else {
//$(rate).addClass('viewAdRateGood');
}
.viewAdRateBad {
color: red;
}
.viewAdRateGood {
color: green;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="view-ad-rating">-0.3</a>
parseInt("-0.3")
//returns -0
parseFloat("-0.3")
//returns -0.3
parseInt("-0.9") // note it doesn't round but just parses the first part
//returns -0
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744992382a4604982.html
评论列表(0条)