在 parseInt() 上返回 NaN
NaN being returned on parseInt()
http://jsfiddle.net/leongaban/fhhmLfab/
在上面的示例中,我有 3 个按钮,橙色、绿色和红色。
悬停时,每个按钮都会显示一个 [-] 和一个 [+] 按钮,class 为 btn_action
。
单击时,我试图从目标颜色按钮中获取数值,然后将其递增或递减 1。
目前我的 parseInt 函数得到 NaN:
$('.btn_action').unbind('click').bind('click', function() {
var type = $(this).data('type').toString();
console.log(color);
console.log(type);
// this is returning NaN, it should be returning 1:
var number = parseInt($('option_'+color).text(), 10);
console.log(number);
if (type === 'plus') {
// number = number + 1;
$('option_'+color).text(number + 1);
console.log(number);
}
});
想知道我哪里出错了吗?
您应该使用 .
作为 class
var number = parseInt($('.option_'+color).text(), 10);
但是你应该使用unary +
一般比parseInt
更高效
var number = +$('.option_'+color).text();
您只需更新选项元素的 jQuery 选择器。正如莱昂所说。
使用$('.option_'+color).text()
代替$('option_'+color).text()
我边看边修改了fiddle的例子:
https://jsfiddle.net/urkjzjsj/
http://jsfiddle.net/leongaban/fhhmLfab/
在上面的示例中,我有 3 个按钮,橙色、绿色和红色。
悬停时,每个按钮都会显示一个 [-] 和一个 [+] 按钮,class 为 btn_action
。
单击时,我试图从目标颜色按钮中获取数值,然后将其递增或递减 1。
目前我的 parseInt 函数得到 NaN:
$('.btn_action').unbind('click').bind('click', function() {
var type = $(this).data('type').toString();
console.log(color);
console.log(type);
// this is returning NaN, it should be returning 1:
var number = parseInt($('option_'+color).text(), 10);
console.log(number);
if (type === 'plus') {
// number = number + 1;
$('option_'+color).text(number + 1);
console.log(number);
}
});
想知道我哪里出错了吗?
您应该使用 .
作为 class
var number = parseInt($('.option_'+color).text(), 10);
但是你应该使用unary +
一般比parseInt
var number = +$('.option_'+color).text();
您只需更新选项元素的 jQuery 选择器。正如莱昂所说。
使用$('.option_'+color).text()
代替$('option_'+color).text()
我边看边修改了fiddle的例子: https://jsfiddle.net/urkjzjsj/