开发者

jQuery: Adding One to Number Inside Element

I'm trying to add one to a number inside a p element with jQuery, but it doesn't work.

$(document).ready(function() {
            function addOne() {
                var number  =   $('p').html();
                return number++;
            }开发者_C百科

            $('p').text(addOne());
        });


You need to parse the number as an Int first, otherwise JavaScript is going to treat it like a string and concatinate it instead.

Also, you want your function to return number + 1, or at least ++number, otherwise you're incrementing after returning, and not actually getting the modified value.

Try this:

$(document).ready(function() {
    function addOne() {
        var number  =   parseInt($('p').html());
        return number + 1;
    }
    $('p').text(addOne());
});


Try this instead:

$(function(){
  $('p').html(function(i, currentHTML){
    return +currentHTML + 1;
  });
});

The original code had two bugs:

  1. The HTML needed to be parsed as an integer. The proper way to do this is with parseInt(html, 10) (parse as a base-10 integer). The shorthand way, if you know what the HTML contains, is +html.

  2. The addOne function returned number++, when it should really return number + 1 or ++number. (The latter example increments number before returning it.)

The corrected code above uses new .html() syntax in jQuery 1.4 (documentation). If you're using jQuery 1.3.x or older, you can use the older .html() syntax with the noted bugs fixed:

$(function(){
  function addOne(){
    var number = +$('p').html();
    return number + 1;
  }
  $('p').html(addOne());
});


Try adding parseInt:

var number = parseInt($('p').html());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜