Javascript,在单击按钮时增加计数器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13328717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript, increment a counter on button click
提问by TechyDude
In javascript, I want to make a counter that increases the value when you click a button.
在 javascript 中,我想制作一个计数器,当您单击按钮时会增加该值。
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.net/techydude/H63As/
小提琴:http: //jsfiddle.net/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?
如何使两行的值显示相同?
采纳答案by Praveen Kumar Purushothaman
You 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
回答by Sudhir Bastakoti
do you mean:
你的意思是:
addBtn.on("click", function() {
counter.html(++value);
return;
});
回答by NullPoiиteя
use
利用
value = parseInt($("#counter").html());
$(function() {
var //valueCount = $("counter").value(),
counter = $("#counter"),
addBtn = $("#add"),
value = parseInt($("#counter").html());
addBtn.on("click", function() {
counter.html(++value );
console.log(value);
return
});
});
回答by Cacho Santa
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 linkabout the operator description of ++ in JavaScript.
在此链接中查看有关 JavaScript 中 ++ 的运算符描述的信息。
Only one line actually changed; however, here is the fiddler linkif you want to test it.
实际上只有一行发生了变化;但是,如果您想测试它,这里是提琴手链接。