jquery .bind() and/or .ready() not working

后端 未结 3 1310
攒了一身酷
攒了一身酷 2021-01-21 15:47

So I have this code:

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

var init;
init = function ()
{
          


        
相关标签:
3条回答
  • 2021-01-21 16:02

    jQuery ready expects a handler, not a function call.

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

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

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

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

    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.

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