jQuery is not finding elements

后端 未结 4 1098
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 06:06

jQuery is not finding any elements. alert($(\"#testbutton\").length); displays 0 every time.

Am I doing something wrong?

My JS / jQuery cod

相关标签:
4条回答
  • 2021-01-21 06:20

    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);
    });
    
    0 讨论(0)
  • 2021-01-21 06:21

    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.

    0 讨论(0)
  • 2021-01-21 06:25

    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.

    0 讨论(0)
  • 2021-01-21 06:42

    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.

    0 讨论(0)
提交回复
热议问题