admin管理员组文章数量:1290379
In javascript, I want to make a counter that increases the value when you click a button.
When I click the add button the first time, the number doesn't increase.
But when I print the value to the console, the result increases.
The fiddle: /
$(function() {
var //valueCount = $("counter").value(),
counter = $("#counter"),
addBtn = $("#add"),
value = $("#counter").html();
addBtn.on("click", function() {
counter.html(value ++); //this value is not incremented.
console.log(value); //this value gets incremented.
return
});
});
How do I make the value show the same for both lines?
In javascript, I want to make a counter that increases the value when you click a button.
When I click the add button the first time, the number doesn't increase.
But when I print the value to the console, the result increases.
The fiddle: http://jsfiddle/techydude/H63As/
$(function() {
var //valueCount = $("counter").value(),
counter = $("#counter"),
addBtn = $("#add"),
value = $("#counter").html();
addBtn.on("click", function() {
counter.html(value ++); //this value is not incremented.
console.log(value); //this value gets incremented.
return
});
});
How do I make the value show the same for both lines?
Share Improve this question edited Jul 7, 2013 at 0:08 Eric Leschinski 154k96 gold badges422 silver badges337 bronze badges asked Nov 11, 2012 at 4:58 TechyDudeTechyDude 1,1654 gold badges16 silver badges24 bronze badges 04 Answers
Reset to default 3You are doing a Post Increment. Make it pre-increment:
addBtn.on("click", function() {
counter.html(++value);
console.log(value);
return
});
Explanation:
// Increment operators
x = 1;
y = ++x; // x is now 2, y is also 2
y = x++; // x is now 3, y is 2
// Decrement operators
x = 3;
y = x--; // x is now 2, y is 3
y = --x; // x is now 1, y is also 1
do you mean:
addBtn.on("click", function() {
counter.html(++value);
return;
});
use
value = parseInt($("#counter").html());
LIVE jSFiddle
$(function() {
var //valueCount = $("counter").value(),
counter = $("#counter"),
addBtn = $("#add"),
value = parseInt($("#counter").html());
addBtn.on("click", function() {
counter.html(++value );
console.log(value);
return
});
});
Try this:
$(function() {
var //valueCount = $("counter").value(),
counter = $("#counter"),
addBtn = $("#add"),
value = $("#counter").html();
addBtn.on("click", function() {
counter.html(++value);
console.log(value);
return
});
});
Take a look in this link about the operator description of ++ in JavaScript.
Only one line actually changed; however, here is the fiddler link if you want to test it.
本文标签: javascriptincrement a counter on button clickStack Overflow
版权声明:本文标题:Javascript, increment a counter on button click - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741039686a2328906.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论