This question already has answers here:
Do DOM tree elements with ids become global variables?

(5个答案)


7年前关闭。




我有以下index.html:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
        </script>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                console.log(foo); // jQuery assumes foo is an id?
            });
        </script>
    </head>
    <body>
        <div id="foo">i'm a div</div>
    </body>
</html>

控制台输出:
<div id="foo">i'm a div</div>
为什么?

最佳答案

这与jQuery无关。

这是因为命名元素(具有IDname属性的元素)成为窗口对象的属性。
console.log(foo)console.log(window.foo);相同

由于您的div是命名元素(id="foo"),因此将其添加到window中。

Named access on window

09-25 17:51
查看更多