简体   繁体   English

全局变量不会更新onclick功能

[英]Global Variable doesn't update onclick function

I have 2 buttons bound with a function that will update a global variable. 我有2个按钮与一个将更新全局变量的函数绑定。 Why do I have to click the button twice so then it'll update said global variable? 为什么我必须单击按钮两次才会更新所说的全局变量? https://jsfiddle.net/q9akn3gz/1/ https://jsfiddle.net/q9akn3gz/1/

<button id="btn1" onclick="myFunc()"> 1 </button>
<button id="btn2" onclick="myFunc()"> 2 </button>

var val = 0;
document.querySelector('#btn1').addEventListener('click',function() {
    val = 200;
});
document.querySelector('#btn2').addEventListener('click',function() {
    val = 400;
});
function myFunc() {
    console.log(val);
}

The reason is that the onclick attribute was encountered before the addEventListener call, so it runs first, so you log first, then update. 原因是在addEventListener调用之前遇到了onclick属性,因此它首先运行,因此您首先记录,然后更新。

It's considered bad practice to use onclick handlers with global functions, please stick to addEventListener . 使用具有全局函数的onclick处理程序被认为是不好的做法,请坚持使用addEventListener

You are calling the function first and updating later. 您首先调用该函数并稍后更新。 Your function prints to the console Before updating the value. 您的功能打印到控制台更新值之前 Try moving the value update to the same function with console.log(val) and using the value operation before that line. 尝试使用console.log(val)将值更新移动到相同的函数,并使用该行之前的值操作。

<button id="btn1" onclick="myFunc(200)"> 1 </button>
<button id="btn2" onclick="myFunc(400)"> 2 </button>

var val = 0
function myFunc(value) {
   val = value;
   console.log(value);
}

remove the onclick attribute event handler, and call the same method in dynamically assigned event handler 删除onclick属性事件处理程序,并在动态分配的事件处理程序中调用相同的方法

check this updated fiddle 检查这个更新的小提琴

<html>
<body>
<button id="btn1">
1
</button>
<button id="btn2">
2
</button>

<script>
var val = 0;
 document.querySelector('#btn1').addEventListener('click',function() {
  val = 200;
  myFunc();
 });
 document.querySelector('#btn2').addEventListener('click',function() {
  val = 400;
  myFunc();
 });
function myFunc() {

 console.log(val);
}
</script>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM