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:
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
.The
addOne
function returnednumber++
, when it should really returnnumber + 1
or++number
. (The latter example incrementsnumber
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());
精彩评论