Javascript,点击按钮增加计数器 [英] Javascript, increment a counter on button click
本文介绍了Javascript,点击按钮增加计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在javascript中,我要创建一个计数器,以在单击按钮时增加该值。
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.
小提琴: 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?
推荐答案
您正在执行发布增量。使其预先递增:
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
这篇关于Javascript,点击按钮增加计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文