admin管理员组

文章数量:1389931

So I have this code:

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

with

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

It suddenly works perfectly. What!??

So I have this code:

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

with

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

It suddenly works perfectly. What!??

Share asked Jun 1, 2011 at 0:57 providenceprovidence 29.5k13 gold badges48 silver badges63 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

jQuery ready expects a handler, not a function call.

// $(document).ready(init()); <-- Not working
$(document).ready(init); <-- Working!

Working example at: http://jsfiddle/marcosfromero/Qwghb/

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

Try this:

$(document).ready(init);

Explanation:

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.

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.

just pass init without parenthesis into the ready function. it is being executed immediately in your case and not on document ready:

$(document).ready(init);

本文标签: javascriptjquery bind() andor ready() not workingStack Overflow