开发者

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

开发者 https://www.devze.com 2022-12-31 02:44 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号