这是我的出价(示例):
// here's the $75 you referenced
var basePrice = 75.00;
// our calculate function (so it can be called on page load and when they change
// their selection from the drop-downs.
function calculate(){
// begin tallying price
var price = basePrice;
// go through each select list
$('select').each(function(){
// grab the selected option's text, then try to extact the
// price from within (e.g. look for "$xx.xx")
var sel = $(':selected',this).text(),
itemprice = parseFloat(sel.match(/\$(\d+(?:\.\d{1.2})?)/)[1], 10);
price += itemprice;
// add it to running total
});
// now display the result back on the page.
$('#price').text(price.toFixed(2));
}
// when the select changes, recalculate
$('select').change(calculate);
// also calculate when the page loads.
calculate();
附录:我建议不要尝试从商品文本中获取价格,而是使用任一value=""
字段(如果可以,尽管它可能会引用该商品的数据库 id),否则,使用data-*
attributes。这方面的一个例子是......
对您的项目进行一些更改(例如)
<option value="1" data-price="10.00">p1-$10</option>
然后对脚本进行更改:
//var sel = $(':selected',this).text(),
// itemprice = parseFloat(sel.match(/\$(\d+(?:\.\d{1.2})?)/)[1], 10);
var itemprice = $(':selected',this).data('price');