jQuery与ready或load事件一起生活

Ste*_*ven 8 jquery dom jquery-tools

我正在使用jQuery Tools工具提示插件,该插件已初始化$('selector').tooltip().我想在任何当前或未来的.tooltipper元素上称呼它.我认为以下内容可行:

$('.tooltipper').live('ready', function(){
  $(this).tooltip()
}
Run Code Online (Sandbox Code Playgroud)

但它没有成功---准备好的事件没有发生.负载相同.我已经读过livequery可以产生我正在寻找的结果,但是肯定有一种方法可以使用jQuery .live()来实现它,考虑到文档说它适用于所有jQuery事件,我相信它ready是一个.

Hur*_*ile 12

引自jQ API(http://api.jquery.com/live/):

在jQuery 1.3.x中,只有以下JavaScript事件(除了自定义事件)才能与.live()绑定:click,dblclick,keydown,keypress,keyup,mousedown,mousemove,mouseout,mouseover和mouseup.

从jQuery 1.4开始,.live()方法支持自定义事件以及所有JavaScript事件.

从jQuery 1.4.1开始,即使是使用live进行聚焦和模糊(映射到更合适,冒泡,聚焦和聚焦的事件).

从jQuery 1.4.1开始,可以指定悬停事件(映射到"mouseenter mouseleave").

.live() 似乎不支持ready事件.


Sea*_*ira 5

添加到HurnsMobile的优秀答案; 看一下bindReady(),这是jQuery每次调用时绑定到文档加载事件的内部调用,$(some_function)或者$(document).ready(some_function)我们看到为什么我们无法绑定到"ready":

bindReady: function() {
        if ( readyBound ) {
            return;
        }

        readyBound = true;

        // Catch cases where $(document).ready() is called after the
        // browser event has already occurred.
        if ( document.readyState === "complete" ) {
            return jQuery.ready();
        }

        // Mozilla, Opera and webkit nightlies currently support this event
        if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", jQuery.ready, false );

        // If IE event model is used
        } else if ( document.attachEvent ) {
            // ensure firing before onload,
            // maybe late but safe also for iframes
            document.attachEvent("onreadystatechange", DOMContentLoaded);

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", jQuery.ready );

            // If IE and not a frame
            // continually check to see if the document is ready
            var toplevel = false;

            try {
                toplevel = window.frameElement == null;
            } catch(e) { //and silently drop any errors 
                    }
                    // If the document supports the scroll check and we're not in a frame:    
            if ( document.documentElement.doScroll && toplevel ) {
                doScrollCheck();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

总结一下,$(some_function)调用一个绑定到的函数:

  • DOMContentLoaded
  • onreadystatechange(DOMContentLoaded)
  • window.load/onload

您最好的选择是绑定到可能创建.tooltipper元素的那些操作,而不是尝试侦听ready事件(仅发生一次).