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.
精彩评论