您好我已经创建了一个javascript函数,可以在更改传递方法时重新计算订单的总计。代码在firefox,chrome和9中工作正常但在8和7中返回NAN,我理解这意味着不是数字。
我尝试过使用parseInt,pareseFloat和Number但是无法理解为什么它在6,7或8中不起作用
我的代码如下
<script type="text/javascript">
function ChangePrice(a)
{
// grabs the delivery price of the selected option i.e 10.99
var price = parseFloat(a);
// grab delivery price which is currently on screen i.e 4.99
old_price = document.getElementById('delivery-sidebar').innerHTML;
// removing the span tags around the function which are not needed
old_price = old_price.replace('<SPAN class=price>','');
old_price = old_price.replace('</SPAN>','');
//grab subtotal price (which does not include delivery) which is currently on screen i.e 34.99
var subtotal = document.getElementById('overall').innerHTML;
// removing the span tags around the function which are not needed
subtotal = subtotal.replace('<span class="price">','');
subtotal = subtotal.replace('</span>','');
subtotal = subtotal.replace('£','');
// converting subtotal to float
subtotal=parseFloat(subtotal);
// if the price of the delivery does not match the price currently on screen
if (price != old_price)
{
//add new price against subtotal
var overall_total = (parseFloat(subtotal))+(parseFloat(price));
// round result to two decimal places i.e 10.99
overall_total=roundNumber(overall_total,2);
// update values on screen
document.getElementById('delivery-sidebar').innerHTML = '<span class="price">£'+price.toFixed(2)+'</span>';
document.getElementById('grand-price').innerHTML = '<span class="price">£'+overall_total.toFixed(2)+'</span>';
}
}
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
</script>
和标记
<ul>
<li>
<input name="shipping_method" value="tablerate_bestway" id="s_method_tablerate_bestway" checked="checked" class="radio validation-passed" onclick="ChangePrice('0')" type="radio">
<label for="s_method_tablerate_bestway">UK Delivery (3 - 7 Working Days) </label>
<span class="price">Free delivery</span>
</li>
</ul>
<dd>
<ul>
<li>
<input name="shipping_method" value="flatrate_flatrate" id="s_method_flatrate_flatrate" class="radio validation-passed" onclick="ChangePrice('10')" type="radio">
<label for="s_method_flatrate_flatrate">Next Day - Orders Before 2pm </label>
<span class="price"><span class="price">£10.00</span></span>
</li>
</ul>
</dd>
答案 0 :(得分:1)
您永远不能依赖于回读创建页面的相同HTML。
如果您在IE中回读<SPAN class="price">
,您实际上会得到<SPAN class=price>
(没有"
),因此您的替换失败,并且解析为数字会返回NaN。
您可以选择依赖.replace('<SPAN class=price>','i')
或更好地为范围指定一个ID:<SPAN id="totalprice" class="price">£xxx</span>
并从innerHTML
获取数值,或者更好地保留所有数值记忆首先。