【发布时间】:2011-09-22 11:54:06
【问题描述】:
我需要为 iframe 中的每个表单附加一个提交侦听器,但我不能使用 jQuery。
这样做的最佳方法是什么?我宁愿不使用window.onload,因为这需要等到图像加载完毕,这可能需要一些时间。显然,$(document).ready() 会很完美,但正如我所说,我不能为此使用 jQuery。
谢谢
【问题讨论】:
我需要为 iframe 中的每个表单附加一个提交侦听器,但我不能使用 jQuery。
这样做的最佳方法是什么?我宁愿不使用window.onload,因为这需要等到图像加载完毕,这可能需要一些时间。显然,$(document).ready() 会很完美,但正如我所说,我不能为此使用 jQuery。
谢谢
【问题讨论】:
Onload 可以解决问题。 Martin 的 jQuery 方法可能会更快。
for(var i=0; i<document.forms.length; i++){
var form = document.forms[i];
form.addEventListener("submit", myListener,false);
}
【讨论】:
自己动手吧 :) 这里是 jQuery 用来准备就绪事件的代码,你需要什么,它是免费的(但请在你的代码中提及它的来源;)
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// 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) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
【讨论】: