【问题标题】:There is an issue with accessing a variable from outside a jquery click function even with a global variable即使使用全局变量,也存在从 jquery click 函数外部访问变量的问题
【发布时间】:2019-08-21 13:28:38
【问题描述】:

我正在尝试单击 jquery 按钮以将所有文本更改为父 div 中的特定文本,但似乎我无法访问 jquery 函数之外的变量

我尝试了许多 stackoverflow 解决方案,但都没有奏效,而且大多数看起来与我的代码非常相似,所以我不明白为什么它不起作用。

<!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>

我希望它打印文本,但它没有,即使使用全局变量,它也无法访问该变量并给我 null 或 undefined。

【问题讨论】:

  • 你为什么要混合原生 javascript 和 jquery?

标签: javascript jquery html function variables


【解决方案1】:

你在for循环中声明了一个全局变量i,如果你想解决问题,你应该用let声明它,

<!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>

【讨论】:

  • 谢谢,我不知道它不工作的问题是因为那个变量。
  • @XeonNetwork 您应该查看stackoverflow.com/questions/750486/… 了解更多信息。永远不要使用这样的全局变量。
  • 好,知道了,以后参考用
猜你喜欢
  • 2011-04-15
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多