jQuery找不到元素 [英] jQuery is not finding elements

查看:234
本文介绍了jQuery找不到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery找不到任何元素. alert($("#testbutton").length);每次显示0.

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

我做错什么了吗?

我的JS/jQuery代码:

(function ($) {
    alert($("#testbutton").length);
}) (jQuery);

我的HTML:

<html>
    <body>
        <div id="header">
            <div class="button" id="testbutton">Test</div>
        </div>
    </body>    
</html>

推荐答案

代码运行时,DOM未准备好,因此该元素不存在.您是不是要这样做(将函数传递给jQuery是$(document).ready(fn)的快捷方式):

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);
});

这篇关于jQuery找不到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆