输出说整数是NaN

时间:2013-11-17 16:56:32

标签: jquery html nan

Fiddle

我正在制作一个社交按钮,我正在努力计算,所以它没有说:

  

1个人喜欢这个

我已成功完成此操作,但当您第二次点击时,它会说:

  

NaN的人喜欢这个

HTML:

 <div id='g'><div id='n' style='display: inline-block'>0</div> people have liked this</div>

jQuery的:

if ($('#n').html() == 1) {
    u = "1 person has liked this";
    $('#g').html(u);
} else {
    var g = parseInt($('#n').html());
    var h = g + 1;
    var v = "people have liked this";
    $('#g').html(h + " " + v);
}

2 个答案:

答案 0 :(得分:4)

这个逻辑要比它需要的复杂得多。除了单个字母id属性,它很难阅读。试试这个:

<button id="b">
    <img src='http://i.imgur.com/ToZz7PB.png'></img>
</button>
<div style='display: inline-block; font-family: Helvetica'>
    <div id='g'>
        <span id='n'>0</span>
        <span class="message">people have liked this</span>
    </div>
</div>
$("#b").click(function () {
    var count = +$('#n').text() + 1;
    var message = count == 1 ? 'person has liked this' : 'people have liked this';
    $('#n').text(count);
    $('.message').text(message);
});

Example fiddle

答案 1 :(得分:1)

当您更新#g的html时,删除#n div,所以当您在代码中查找它时,它不存在..