0

I'm trying to make a jquery button click to change all text to a specific text in the parent div but it seems that I can't access variables that are outside of the jquery function

I tried many stackoverflow solutions but none of them worked and most of them looked very similar to my code so I don't understand why it didn't work.

<!DOCTYPE html>
<html>

<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
</head>

<body>

    <div id="test">
        <p>Click the button to get the tag names of the body element's children.</p>
    </div>
    <button>Try it</button>

    <p id="demo"></p>

    <script>
        $(document).ready(function() {

            var Dropdownchildren = document.getElementById("test").children
            for (i = 0; i < Dropdownchildren.length; i++) {
                console.log(Dropdownchildren[i].innerHTML)
                    // will work
                $(Dropdownchildren[i]).click(function() {
                    console.log(Dropdownchildren[i].innerHTML)
                        // not work
                })
            }

        })
    </script>

</body>

</html>

I expected it to print the text but it didn't and even with global variables it couldn't access the variable and give me null or undefined.

Eric Wang
  • 419
  • 2
  • 6
  • 23

1 Answers1

0

You are declaring a global variable i in for loop you should declare it with let if you want to solve problem,

<!DOCTYPE html>
<html>

<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
</head>

<body>

    <div id="test">
        <p>Click the button to get the tag names of the body element's children.</p>
    </div>
    <button>Try it</button>

    <p id="demo"></p>

    <script>
        $(document).ready(function() {

            var Dropdownchildren = document.getElementById("test").children
            for (let i = 0; i < Dropdownchildren.length; i++) {
                console.log(Dropdownchildren[i].innerHTML)
                    // will work
                $(Dropdownchildren[i]).click(function() {
                    console.log(Dropdownchildren[i].innerHTML)
                        // not work
                })
            }

        })
    </script>

</body>

</html>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • Thank you, I didn't know the issue it wasn't working was because of that variable. – Eric Wang Mar 31 '19 at 02:56
  • @XeonNetwork You should see https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example/750506#750506 for more information. Donot ever use global variables like that. – Maheer Ali Mar 31 '19 at 02:59
  • Okay, got it, I will use it for future reference – Eric Wang Mar 31 '19 at 03:09