问题
jQuery is not finding any elements. alert($("#testbutton").length); displays 0 every time.
Am I doing something wrong?
My JS / jQuery code:
(function ($) {
alert($("#testbutton").length);
}) (jQuery);
My HTML:
<html>
<body>
<div id="header">
<div class="button" id="testbutton">Test</div>
</div>
</body>
</html>
回答1:
When your code runs the DOM is not ready so the element doesn't exist. Did you mean to do this instead (passing a function to jQuery is a shortcut for $(document).ready(fn)):
$(function () {
alert($("#testbutton").length);
});
回答2:
If you write jQuery script in the head using:
(function() {
...
})();
it doesn't work because it may execute the script before loading the content of the body page.
Use:
$(document).ready(function() {
...
});
or move your script at the footer.
回答3:
Call it on document ready as you can see here: http://jsfiddle.net/SwQUH/
$(document).ready(function() {
alert($("#testbutton").length);
});
If you just call it like that, the DOM isn't 'ready' and the HTML element doesnt yet exist.
回答4:
try the following
<script type="text/javascript">
And first ensure thers no error in loading jquery
put an alert on load of DOM and check if everything is fine.
来源:https://stackoverflow.com/questions/12301605/jquery-is-not-finding-elements