jQuery .bind()和/或.ready()不起作用 [英] jquery .bind() and/or .ready() not working

查看:94
本文介绍了jQuery .bind()和/或.ready()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这段代码:

var bindAll;
bindAll = function ()
{
    $('#somediv').bind('mouseover', function(){do something});
};

var init;
init = function ()
{
    bindAll();
    ...
};

$(document).ready(init());

,它不起作用.但是,如果我通过替换将绑定放在计时器上

and it does not work. But if I put the bind on a timer by replacing:

bindAll();

tt = setTimeout('bindAll()', 1000);

它突然变得完美.什么!?

It suddenly works perfectly. What!??

推荐答案

您没有将init传递给$(document).ready,而是传递了init返回的任何内容.

You aren't passing init to $(document).ready, you're passing whatever init returns.

尝试一下:

$(document).ready(init);

说明:

当您尝试传递函数时,实际上是在运行它.在您运行它时,DOM还没有准备就绪,因此未绑定到该元素,因为它不存在.

When you were trying to pass the function, you were actually running it. At the time of you running it, the DOM wasn't ready, so the bindings to the element didn't take place, because it didn't exist.

完成超时后,之所以起作用,是因为DOM完成所需的时间不到一秒钟,这意味着在它运行之前,元素已经存在,因此它可以绑定事件.

When you did the timeout, it worked because it took less then one second for the DOM to finish, which means by the time it gets run, the element is there, so it can bind the event.

这篇关于jQuery .bind()和/或.ready()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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