each() function returning Null or Objects
Hi I am newbie in programming and I am trying to learn and make it work with each(). Bear with me. I try my best to learn from here and you.
- I am trying to go through the item per product in a catalog for the specific prices: either original and sale from the page.
- then calculate the % for discount
- print discount %
- check to compare the percent to color the background: brown, yellow and red.
Now, I test each line to see if it works or not.
salecost = $(this).find('#sale').html();
returns a few nulls before displays amount with dollar signs. Weird couldn't figure that one out. Replace() isn't working right - couldn't get it working. It is supposed to remove dollar sign.
Also, I am not sure how it goes with compare -- do i write statement correctly?
Thank you in advance for the help
var salecost;
var originalcost;
var percentDiscount;
var percent;
function calculate(sale, original)
{
percentDiscount = eval((sale/original)*100);
document.getElementById("percentoff").innerHTML=parseInt(percentDiscount) + '%';
}
$(document).ready(function(index){
$('.item').each(function(){
salecost = $(this).find('#sale').html();
salecost = salecost.replace(/[^\d\.]/g,"");
alert (salecost);
originalcost = $('#sale').html();
originalcost = originalcost.replace(/[^\d\.]/g,"");
alert (originalcost);
percent = calculate(salecost,originalcost);
alert(percent);
if(percent<30)
{
$("div#percentoff"开发者_如何学运维).css({"background-color":"brown", "padding":"5px 0"});
}
if(percent<50){
$("div#percentoff").css({"background-color":"yellow", "padding":"5px 0"});
}
if(percent<70){
$("div#percentoff").css({"background-color":"red", "padding":"5px 0"});
}
});
});
This is not required
$(this).find('#sale').html();
You can replace this using
$("#sale").html();
since id will be unique in a document. If you have more than one element with the same id then your HTML is invalid.
Edit
Remove the id from the span tag.
<span class="price">S$319</span>
This will find all the spans[here only 1] with class name price
inside the parent div. No need to use .html()
here, you can use .text()
$(this).find('span.price').text();
- You should move your var statements to within the each function so they're not global.
- You don't need to you the eval, (sale/original)*100 will work by it self.
It's better to use consistent style, your calculate function could be written using jquery.
$("#percentoff").html(percentDiscount) + '%');
casting is unnecessary for most cases in javascript, concatenating a number with a string will produce a string.
- your calculate function should
return percentDiscount;
- Instead of using .css() it would be better to use .addClass that way it's easy to undo with .removeClass, the style is all the the style sheet and you can use jquery to select the elements with the class.
精彩评论