jQuery is not finding elements

僤鯓⒐⒋嵵緔 提交于 2019-12-01 23:01:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!