jQuery与ready或load事件一起生活

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

 $('.tooltipper').live('ready', function(){ $(this).tooltip() } 

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

引自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开始,可以指定hover事件(映射到“mouseenter mouseleave”)。

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

添加到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(); } } } 

总而言之, $(some_function)调用一个绑定到的函数:

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

最好的办法是绑定那些可能创建新的.tooltipper元素的操作,而不是试图监听ready事件(只发生一次)。

HurnsMobile是对的。 JQuery live不支持ready事件。

这就是我创建一个结合了两者的插件的原因。 您注册了一次回调,然后您需要为手动添加的内容调用一次插件。

 $.liveReady('.tooltipper', function(){ this.tooltip() }); 

然后在创建新内容时:

 element.html(somehtml); element.liveReady(); 

要么

 $('
...').appendTo($('body')).liveReady();

这里有一个演示: http : //cdn.bitbucket.org/larscorneliussen/jquery.liveready/downloads/demo.html

在这里查看介绍性post: http : //startbigthinksmall.wordpress.com/2011/04/20/announcing-jquery-live-ready-1-0-release/


另请查看http://docs.jquery.com/Plugins/livequery ,它会监听dom上的更改。