简体   繁体   中英

Global Variable doesn't update onclick function

I have 2 buttons bound with a function that will update a global variable. Why do I have to click the button twice so then it'll update said global variable? 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.

It's considered bad practice to use onclick handlers with global functions, please stick to 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.

<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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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