简体   繁体   中英

jQuery .ready() automatically defining variables for each element with ID in DOM

I have noticed some unexpected behaviour when using the jQuery .ready() function, whereby afterwards you can reference an element in the DOM simply by using its ID without prior definition:

<html>
<script src="jquery.js"></script>
<script>
        $(document).ready(function() {
                myowndiv.innerHTML = 'wow!'
        });
</script>
<body>
        <div id="myowndiv"></div>
</body>

</html>

I would have expected to have to declare and assign myowndiv with document.getElementById("myowndiv"); or $("#myowndiv"); before I could call innerHTML or anything else on it?

Is this behaviour by design? Can anyone explain why? My fear is that if I don't notice and refactor and end up not using .ready() or even using jQuery at all then my code will fail to execute with lots of undefined errors.

Cheers!

That is a (terrible) Internet Explorer-only "feature". Yet again Microsoft fail at life.... sigh. You will need to do var foo = document.getElementById('foo'); for cross-browser compatibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM