如果变量未定义

if variable is undefined

这可能看起来像重复的,但我无法让它工作。 我想要做的是每次点击,获得一定的价值,将其添加到 cookie 中已有的值,并用新的总数替换 cookie 值。而且我仍然没有收到数字错误

var nextqurl = $(".nav-next a").attr('href');
    var curcookie = $.cookie('test');
    var initscore = 0;
    alert(curcookie);
    $(".answer").click(function(){
        var score = $(this).attr('id');
        var updatedscore = parseInt(curcookie) + parseInt(score);
        if (typeof curcookie === 'undefined') {
            $.cookie('test',initscore, {path: '/'});
            }
        else
        {
            $.cookie('test',updatedscore, {path: '/'});
            }
        $.cookie('test',updatedscore, {path: '/'});
        window.location.replace(nextqurl);
        });
    }); 

p.s。 cookie 工作正常

试试这个...

var curcookie = parseInt($.cookie('test')) || 0;

并从处理程序中的 parseInt(curcookie) 中取出 parseInt