jquery假设元素id?正常的行为?

mzm*_*m56 11 javascript jquery

我有以下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>
Run Code Online (Sandbox Code Playgroud)

控制台输出:

<div id="foo">i'm a div</div>

为什么?

c.P*_*.u1 7

这与jQuery无关.

这是因为命名元素(具有IDname属性的元素)成为窗口对象的属性.

console.log(foo) 是完全相同的 console.log(window.foo);

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

在窗口上命名访问