【问题标题】:How to attach a submit listener to all forms without jQuery如何在没有 jQuery 的情况下将提交侦听器附加到所有表单
【发布时间】:2011-09-22 11:54:06
【问题描述】:

我需要为 iframe 中的每个表单附加一个提交侦听器,但我不能使用 jQuery。

这样做的最佳方法是什么?我宁愿不使用window.onload,因为这需要等到图像加载完毕,这可能需要一些时间。显然,$(document).ready() 会很完美,但正如我所说,我不能为此使用 jQuery。

谢谢

【问题讨论】:

    标签: javascript event-listener


    【解决方案1】:

    Onload 可以解决问题。 Martin 的 jQuery 方法可能会更快。

    for(var i=0; i<document.forms.length; i++){
      var form = document.forms[i];
      form.addEventListener("submit", myListener,false);
    }
    

    【讨论】:

    • 好吧,你们都完美地回答了问题的不同部分,我接受哪一个?!
    • 好吧,由你决定。我已经回答了你的主要问题。接受对你帮助最大的那个。
    • 哇,这是完美的答案。经过 20 分钟的研究,我找到了在同一页面中处理多个表单的提交事件侦听器的解决方案,而没有 id。谢谢
    【解决方案2】:

    自己动手吧 :) 这里是 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();
                }
            }
        },
    

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2016-08-29
      相关资源
      最近更新 更多