最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Adding One to Number Inside Element - Stack Overflow

programmeradmin1浏览0评论

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++;
            }

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

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++;
            }

            $('p').text(addOne());
        });
Share Improve this question asked Mar 26, 2010 at 1:20 EspressoEspresso 4,7521 gold badge25 silver badges33 bronze badges 1
  • Are you getting incorrect results or no results at all? If you're not getting any results, check the Error Console (in Firefox), as there may be something else going on. If you're getting results, but wrong results, post them here-- that way we can better understand the issue. – Blank Commented Mar 26, 2010 at 1:28
Add a ment  | 

3 Answers 3

Reset to default 5

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)

  1. 暂无评论