Manipulation of HTML values in a class using jQuery
I have the following HTML structure
<div class="something">
<div class="amount">$10</div>
</div>
<div class="something">
<div class="amount">$20</div>
</div>
<div class="something">
<div class="amount">$30</div>
</div>
<div class="something">
<div class="amount">$40</div>
</div>
I want to manipulate the amo开发者_C百科unt displayed on the page based on a condition. Eg: Increase the fontsize if the amount is above $25. I am able to select and manipulate the style without the condition. I tried using makeArray to store the values from the amount class but i am not sure how to do the conditional check.
$(".amount").each(function(){
var amount = parseInt($(this).text().replace("$",""));
$(this).css({fontSize:amount});
});
Online demo: http://jsfiddle.net/HU9mV/
$("div.something div.amount").addClass(function () {
var amount = parseFloat($(this).text().replace("$", ""));
if (!isNaN(amount) && amount > 25) {
return "special";
}
});
This adds the CSS class "special" to every div.amount that has a value greater than 25.
The following would be one way to do it:
// iterate through all .amount divs
$('div.amount').each(function() {
var jqThis = $(this);
var text = jqThis.text().replace("$","");
// if the dollar value as a number is greater than 25, change the font
if((+text) > 25) {
this.css('font-size', '16px');
}
});
$('.something > .amount').each(function() {
var amt = $(this).text().substring(1);
if(parseInt(amt) > 25) {
$(this).addClass('highlight');
}
});
parseFloat can be used also if you expect floating point numbers.
As written you could use the jQuery.each method like so.
$("div.something>div.amount").each(function(i,e) {
$me = $(e);
if($me.text().substr(1) > 25) {
$me.animate({ fontSize: 25 }, 800)
}
});
This is overkill for your exact question but would give you many options for conditional checks and further actions. For instance the i (index) could be used to tell which row(s) were changed and the e (element) variable makes the entire inner div available for manipulation.
精彩评论