我编写了一个jQuery插件,每0.5秒检查一次工具栏是否有请求的元素。
(function( $ ) {
/**
* Wait until element has finish loading requested elements, then execute callback
* @param string element Element to wait for
* @param object callback Callback to execute
* @param integer timeout Optional timeout to stop testing the element if none of the requested element was found
*/
$.fn.waitEdToolbarLoaded = function( element, callback, timeout ) {
var interval = null;
var target = this;
var timeout = typeof timeout !== \'undefined\' ? timeout : 5000;
interval = window.setInterval(
function () {
var length = $( target ).find( element ).length;
timeout -= 500;
if( 0 > timeout ) {
window.clearInterval( interval );
}
if( 0 < length ) {
window.clearInterval( interval );
callback();
}
},
500
);
}
})( jQuery );
以及如何使用它的简单示例
jQuery( document ).ready(
function( $ ) {
// callback to execute if the requested element was found
function alarm() { alert( \'Toolbar ready!\' ); }
// wait for elements
$( \'#edtoolbar\' ).waitEdToolbarLoaded( \'p\', alarm );
// create the elements after 3 seconds
setTimeout(
function () {
for ( var i=1; i<4; i++ ) { $( \'#edtoolbar\' ).append( \'<p>\'+i+\'</p>\' ); }
},
3000
);
}
);
也许插件需要一些改进,但它也可以在其他情况下使用。