我正在尝试制作一个只能从0到最大10的计数器,现在我可以在计数器中添加和删除数字,但由于某种原因我的if / else永远不会起作用,无论如何我把它们放在哪里我是一个真正的javascript菜鸟,所以如果有人能给我一些建议,将非常感谢。
这是我的代码:
<script type="text/javascript">
var clicks = 0;
if (clicks < 0) {
clicks = 0;
document.getElementById("ticketAmmount").innerHTML = clicks;
}
function onClick() {
clicks += 1;
document.getElementById("ticketAmmount").innerHTML = clicks;
};
function offClick() {
clicks -= 1;
document.getElementById("ticketAmmount").innerHTML = clicks;
}
我也试过这个:但是计数器给了我NaN
<script type="text/javascript">
var clicks = 0;
function onClick() {
if (clicks < 0) {
clicks = 0;
document.getElementById("ticketAmmount").innerHTML = clicks;
} else {
clicks += 1;
document.getElementById("ticketAmmount").innerHTML = clicks;
}
};
function offClick() {
clicks -= 1;
document.getElementById("ticketAmmount").innerHTML = clicks;
}
</script>
答案 0 :(得分:2)
你几乎是对的,把你的if
放在你的onClick和offClick函数中,然后删除第一个(看起来没用):
var clicks = 0;
document.getElementById("ticketAmmount").innerHTML = clicks;
function onClick() {
clicks += 1;
if (clicks > 10) {
clicks = 10;
}
document.getElementById("ticketAmmount").innerHTML = clicks;
};
function offClick() {
clicks -= 1;
if (clicks < 0) {
clicks = 0;
}
document.getElementById("ticketAmmount").innerHTML = clicks;
}
答案 1 :(得分:2)
它并不复杂:
var minVal = 0, maxVal = 10, clicks = 0,
display = document.getElementById("ticketAmmount");
function countUp(){
clicks = Math.min( maxVal, clicks+1 );
display.innerHTML = clicks;
}
function countDown(){
clicks = Math.max( minVal, clicks-1 );
display.innerHTML = clicks;
}
&#13;
<button onclick="countDown();">-</button>
<span id="ticketAmmount">0</span>
<button onclick="countUp();">+</button>
&#13;
答案 2 :(得分:1)
if (clicks < 0)
仅在页面加载时被调用一次,并且在您设置clicks = 0
后立即被调用,因此它永远不会满足条件。您需要将该逻辑放在onClick
和offClick
中,或者将其提取到某个方法中,例如:
var clicks = 0;
function resetClicks() {
if (clicks < 0) {
clicks = 0;
document.getElementById("ticketAmmount").innerHTML = clicks;
}
}
function onClick() {
clicks += 1;
document.getElementById("ticketAmmount").innerHTML = clicks;
resetClicks();
};
function offClick() {
clicks -= 1;
document.getElementById("ticketAmmount").innerHTML = clicks;
resetClicks();
}