在parseInt()上返回NaN

时间:2015-02-22 22:18:46

标签: javascript jquery parseint

http://jsfiddle.net/leongaban/fhhmLfab/

在上面的示例中,我有3个按钮,橙色,绿色和红色。

在悬停时,每个人都会显示一个[ - ]和一个[+]按钮,其类别为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);
    }
});

enter image description here

关于我哪里出错的想法?​​

2 个答案:

答案 0 :(得分:3)

您应该使用.进行课程

var number = parseInt($('.option_'+color).text(), 10);

但是你应该使用一元+通常比parseInt

更有效
var number = +$('.option_'+color).text();

答案 1 :(得分:1)

您只需要更新选项元素的jQuery选择器。正如莱昂所说。

使用$('.option_'+color).text()代替$('option_'+color).text()

我看着它修改了小提琴的例子: https://jsfiddle.net/urkjzjsj/

相关问题