admin管理员组文章数量:1326493
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
3 Answers
Reset to default 5You 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());
本文标签: javascriptjQuery Adding One to Number Inside ElementStack Overflow
版权声明:本文标题:javascript - jQuery: Adding One to Number Inside Element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742204327a2432532.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论