状态未更新全局范围的变量

时间:2018-08-14 17:36:41

标签: javascript

我不明白为什么计数不会更新。它的作用域是全局范围,并且我已验证单击加/减按钮时会触发功能。由于我是编程新手,因此在此阶段发现的其他示例对于我来说有点太复杂了。

//target the proper elements
let add = document.getElementById('add');
let subtract = document.getElementById('subtract');
let span = document.getElementById('result');

//starting data
let count = 0;

//add to count
function addCount() {
    count++;
}

//subtract from count
function subtractCount() {
    count--;
}

//display the count
span.innerHTML = count;

/************Event Listeners*************/
add.addEventListener('click', addCount);
subtract.addEventListener('click', subtractCount);

2 个答案:

答案 0 :(得分:1)

计数正在变化。问题是您没有更改显示。这应该起作用:

# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");

# Close opend file
fo.close()

答案 1 :(得分:0)

let add = document.getElementById('add');
let subtract = document.getElementById('subtract');
let span = document.getElementById('result');

//starting data
let count = 0;

//add to count
function addCount() { 
  count++;
  span.innerHTML = count; // you need to update span for every count update
}

//subtract from count
function subtractCount() {
  count--;
  span.innerHTML = count; // you need to update span for every count update
}

//display the count
span.innerHTML = count; // this code runs only one time

/************Event Listeners*************/
add.addEventListener('click', addCount);
subtract.addEventListener('click', subtractCount);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button id='add'>add</button>
  <button id='subtract'>subtract</button>
  <span id='result'></span>
</body>
</html>