我正在尝试在首次加载该页面时运行一个函数,并在点击products
/ quantities
后,计算并显示用户所选内容的总价格。
一切似乎进展顺利,但我的price
变量不断返回NaN
。不知道我现在缺少什么。我做了一些搜索,parseInt()
似乎就是我想要的,但它仍然会返回NaN
。
提前感谢您的帮助。
jQuery(document).ready(function() {
var bessie = function() {
//Pull html code for plus/minus qty selector
var qtyCode = jQuery('.qtyswitcher-qty').html();
//Pull the current price text that is up on the website
var bender = jQuery('.price').text();
//Remove currency symbol and convert price text to a number
var leela = Number( bender.replace(/[^0-9\.]+/g,""));
//Get value of qty that is currently selected
var qty = jQuery('#qtyswitcher-clone-qty').attr('value');
//Number() above was resulting in NaN, so trying parseInt to make it show a number
var price = parseInt(jQuery(leela).val(), 10);
/*More stuff that didn't work
leela.val();
parseInt(leela);
*/
//multiply price by qty to get the total for the users current selection
var total = price * qty;
//New html that will be inserted into the page
var newContent = '<p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + qtyCode + '<p class="multiply3">=</p> <p class="multiply">' + '$' + total + '</p>';
//New html being inserted
jQuery(".qtyswitcher-qty").replaceWith(newContent);
};
jQuery('.switcher-label').click(bessie);
jQuery('#qtyswitcher-oneless').click(bessie);
jQuery('#qtyswitcher-onemore').click(bessie);
bessie();
});
答案 0 :(得分:1)
在这一行:
var price = parseInt(jQuery(leela).val(), 10);
// ------------------^^^^^^^^^^^^^^^^^^^
您将一个数字传递到jQuery
,这会使其尝试在文档中将该数字设置为标记(如div
)。它找不到任何东西,所以它会返回一个空集。在空集上调用.val()
可为您undefined
,当通过parseInt
进行解析时,会NaN
。
我怀疑你不想这样做,而是直接使用leela
:
var price = parseInt(leela, 10);
如果你这样做,你不希望在前一行Number
:
var leela = Number( bender.replace(/[^0-9\.]+/g,""));
将它保留为字符串,稍后您将解析它。
尽管如此,整个事情看起来有点令人费解。如果您有价格和数量,那么只需:
var bessie = function(){
// Pull html code for plus/minus qty selector
var qtyCode = jQuery('.qtyswitcher-qty').html();
// Pull the current price text that is up on the website,
// removing the currency symbol
var price = jQuery('.price').text().replace(/[^0-9\.]+/g,"");
// Get value of qty that is currently selected
// NOTE: I'm assuming here that this value can never be blank
var qty = jQuery('#qtyswitcher-clone-qty').val();
// Multiply price by qty to get the total for the user's current selection
// The strings will be coerced to numbers, but if you want to ensure
// that base 10 is used even if something has a leading 0 or some
// such, you could use parseFloat here (you presumably don't want
// parseInt, I can't imagine "price" is a whole number in dollars)
var total = price * qty;
// Or: var total = parseFloat(price) * parseFloat(qty);
// New html that will be inserted into the page
var newContent = '<p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + qtyCode + '<p class="multiply3">=</p> <p class="multiply">' + '$' + total + '</p>';
//New html being inserted
jQuery(".qtyswitcher-qty").replaceWith(newContent);
};