Why did this js Mini Program appear NaN??

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        window.onload = function() {

            var oTxt1 = document.getElementById("txt1");

            var oTxt2 = document.getElementById("txt2");

            var oBtn = document.getElementById("btn1");



            var n1 = parseFloat(oTxt1.value);

            var n2 = parseFloat(oTxt2.value);

            oBtn.onclick = function() {

                alert(n1+n2);

            };

        };

    </script>

</head>

<body>

<input type="text" id="txt1" >

<input type="text" id="txt2" >

<input type="button" id="btn1" value="=">

</body>

</html>

my younger brother recently encountered a problem in self-study js,. I am a little confused today. I hope some great god can take a look at it

.
  var n1 = parseFloat(oTxt1.value);

  var n2 = parseFloat(oTxt2.value);

if the above two variables are defined outside oBtn.onclick = function () , NaN will pop up, but not if they are inside. Thank you!

Apr.07,2021

about the timing of execution, you are using

oBtn.onclick = function() {
                alert(n1+n2);
            };

in fact, the timing of assignment statements for N1 and N2 is window.onload . At that time, there was no value in input, so it was NaN,

.
Menu