RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 688566
Accepted
Yuri
Yuri
Asked:2020-07-08 00:06:40 +0000 UTC2020-07-08 00:06:40 +0000 UTC 2020-07-08 00:06:40 +0000 UTC

页面加载后运行脚本 (DOM)

  • 772

加载 DOM 后应该运行一个脚本,因为它有一个 DOM 调用:

var element = document.getElementById('element');
element.style.color = 'red';

我怎样才能运行这个脚本,以便脚本对 DOM 的访问能够正常工作?

javascript
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    Yuri
    2020-07-08T00:06:40Z2020-07-08T00:06:40Z

    对于那些不知道为什么可以访问表单元素的脚本不起作用的人<script>document.getElementById('element').style.color = 'red';</script>:

    该脚本尝试与页面上的 HTML 元素交互,这些元素的代码比脚本本身的代码低。因此,脚本已经加载,但您需要与之交互的元素尚未加载。出于这个原因,什么都行不通。

    Javascript 语言的特点是它的代码是按顺序逐行执行的,就像它们写在源代码中一样。

    解决此问题的选项:

    1. 一种简单的方法是<script></script>在所有元素之后将其移动到主体。通过这种安排,DOM 将首先加载,然后是脚本。例子:

      <body>
         <div>...</div>
         <script>
            // Ваш скрипт
         </script>
      </body>
      
    2. 所有初学者想到的最简单的方法是在window.onload. 例子:

      window.onload = function() {
         // Ваш скрипт
      };
      

    您也可以通过window.addEventListener('load', ...);或添加window.attachEvent('onload', ...);

    但是这种方法有一个缺点:如果网站页面上有很多图片需要半小时加载,那么脚本只有在所有图片都加载完之后才会执行,这样会耗费很多时间。

    另一个缺点是您不能以这种方式指定多个函数。那些。如果您window.onload在代码中使用了两次,那么第二个函数将擦除第一个函数。但为了解决这个问题,我制作了一个有趣的拐杖:

        var windowOnloadAdd = function (event) {
           if ( window.onload ){
              window.onload = window.onload + event;
           } else {
              window.onload = event;
           };
        };
    
        windowOnloadAdd(function() {
           // Ваш скрипт
        });
    
    1. 一个有趣的选择是介于第一点和第二点之间。创建一个自定义函数并通过主体末尾的脚本调用它。例子:

      在JS中:

      function onload() {
         // Ваш скрипт
      };
      

      在 HTML 中:

      <body>
         ...
         <script>
            onload();
         </script>
      </body>
      
    2. 最流行的技巧之一是为正文设置事件onload。例子:

      在JS中:

      function myFunc() {
         // Ваш скрипт
      };
      

      在 HTML 中:

      <body onload="myFunc()">...</body>
      
    3. enStackOveflow 的方式是通过document.onreadystatechange和函数运行document.readyState。例子:

      document.onreadystatechange = function(){
         if(document.readyState === 'complete'){
            // Ваш скрипт
         }
      }
      
    4. 一种相当新的方法是通过 DOMContentLoaded. 例子:

      document.addEventListener('DOMContentLoaded', function() {
         // Ваш скрипт
      }, false);
      

      IE9+开始支持该方法

    5. 好吧,图书馆的选择出现了。还有我们的第一个JQuery ScriptJava 库。例子:

      $$r(function() {
         // Ваш скрипт
      });
      

      [下载库]

    6. 适用于任何使用 JQuery 的人的一个选项是使用 JQuery :)。例子:

      选项1:

      $(function() {
         // Ваш скрипт
      });
      

      选项 2:

      $(document).ready(function() {
         // Ваш скрипт
      });
      

      [图书馆链接]

    7. 还有一个使用 UI YAHOO 的选项。不幸的是,要使这种方法起作用,我们需要包含多达 2 个脚本:yahoo-min和event-min. 例子:

      YAHOO.util.Event.onDOMReady(function(){
         // Ваш скрипт
      });
      

      [下载 "yahoo-min.js" ] | [下载 "event-min.js" ]

    8. 最有效的选择是使用 enStackOverflow 的自写函数。在 IE8 中工作:

      变种准备好=(功能(){

        var readyList,
            DOMContentLoaded,
            class2type = {};
            class2type["[object Boolean]"] = "boolean";
            class2type["[object Number]"] = "number";
            class2type["[object String]"] = "string";
            class2type["[object Function]"] = "function";
            class2type["[object Array]"] = "array";
            class2type["[object Date]"] = "date";
            class2type["[object RegExp]"] = "regexp";
            class2type["[object Object]"] = "object";
      
         var ReadyObj = {
             // Is the DOM ready to be used? Set to true once it occurs.
             isReady: false,
             // A counter to track how many items to wait for before
             // the ready event fires. See #6781
             readyWait: 1,
             // Hold (or release) the ready event
                 holdReady: function( hold ) {
                 if ( hold ) {
                     ReadyObj.readyWait++;
                 } else {
                     ReadyObj.ready( true );
                 }
             },
             // Handle when the DOM is ready
             ready: function( wait ) {
                 // Either a released hold or an DOMready/load event and not yet ready
                 if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
                     // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                     if ( !document.body ) {
                         return setTimeout( ReadyObj.ready, 1 );
                     }
      
                     // Remember that the DOM is ready
                     ReadyObj.isReady = true;
                     // If a normal DOM Ready event fired, decrement, and wait if need be
                     if ( wait !== true && --ReadyObj.readyWait > 0 ) {
                         return;
                     }
                     // If there are functions bound, to execute
                     readyList.resolveWith( document, [ ReadyObj ] );
      
                     // Trigger any bound ready events
                     //if ( ReadyObj.fn.trigger ) {
                     //    ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
                     //}
                 }
             },
             bindReady: function() {
                 if ( readyList ) {
                     return;
                 }
                 readyList = ReadyObj._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( ReadyObj.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", ReadyObj.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", ReadyObj.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();
                     }
                 }
             },
             _Deferred: function() {
                 var // callbacks list
                     callbacks = [],
                     // stored [ context , args ]
                     fired,
                     // to avoid firing when already doing so
                     firing,
                     // flag to know if the deferred has been cancelled
                     cancelled,
                     // the deferred itself
                     deferred  = {
      
                         // done( f1, f2, ...)
                         done: function() {
                             if ( !cancelled ) {
                                 var args = arguments,
                                     i,
                                     length,
                                     elem,
                                     type,
                                     _fired;
                                 if ( fired ) {
                                     _fired = fired;
                                     fired = 0;
                                 }
                                 for ( i = 0, length = args.length; i < length; i++ ) {
                                     elem = args[ i ];
                                     type = ReadyObj.type( elem );
                                     if ( type === "array" ) {
                                         deferred.done.apply( deferred, elem );
                                     } else if ( type === "function" ) {
                                         callbacks.push( elem );
                                     }
                                 }
                                 if ( _fired ) {
                                     deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
                                 }
                             }
                             return this;
                         },
      
                     // resolve with given context and args
                     resolveWith: function( context, args ) {
                         if ( !cancelled && !fired && !firing ) {
                             // make sure args are available (#8421)
                             args = args || [];
                             firing = 1;
                             try {
                                 while( callbacks[ 0 ] ) {
                                     callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
                                 }
                             }
                             finally {
                                 fired = [ context, args ];
                                 firing = 0;
                             }
                         }
                         return this;
                     },
      
                     // resolve with this as context and given arguments
                     resolve: function() {
                         deferred.resolveWith( this, arguments );
                         return this;
                     },
      
                     // Has this deferred been resolved?
                     isResolved: function() {
                         return !!( firing || fired );
                     },
      
                     // Cancel
                     cancel: function() {
                         cancelled = 1;
                         callbacks = [];
                         return this;
                     }
                 };
      
             return deferred;
         },
         type: function( obj ) {
             return obj == null ?
                 String( obj ) :
                 class2type[ Object.prototype.toString.call(obj) ] || "object";
         }
      

      } // Internet Explorer 的 DOM 就绪检查函数 doScrollCheck() { if ( ReadyObj.isReady ) { return; }

         try {
             // If IE is used, use the trick by Diego Perini
             // http://javascript.nwbox.com/IEContentLoaded/
             document.documentElement.doScroll("left");
         } catch(e) {
             setTimeout( doScrollCheck, 1 );
             return;
         }
      
         // and execute any waiting functions
         ReadyObj.ready();
      

      } // 文档就绪方法的清理函数 ReadyObj.ready(); };

      } else if ( document.attachEvent ) { DOMContentLoaded = function() { // 至少确保 body 存在,以防 IE 变得有点过分热心(ticket #5443)。if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); ReadyObj.ready(); } }; } function ready( fn ) { // 附加监听器 ReadyObj.bindReady();

         var type = ReadyObj.type( fn );
      
            // Add the callback
            readyList.done( fn );//readyList is result of _Deferred()
        }
        return ready;
        })();
      
     
    
        ready(function() {
           // Ваш скрипт
        });
    
    1. 最后,最奇怪但并不总是有效的选项是使用 setTimeout。例子:

      setTimout(function() { // 你的脚本 }, 3000);

    这些是我遇到的所有选项,但也许不是唯一的选项,因为其他程序员可以想出自己的功能来解决这个问题。

    使用哪个选项取决于您:)

    • 31
  2. Bez Cepera
    2020-09-06T01:56:41Z2020-09-06T01:56:41Z

    他们还忘记了 defer 属性。html书

    <script defer>
      // код
    </script>
    
    • 5

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    Python 3.6 - 安装 MySQL (Windows)

    • 1 个回答
  • Marko Smith

    C++ 编写程序“计算单个岛屿”。填充一个二维数组 12x12 0 和 1

    • 2 个回答
  • Marko Smith

    返回指针的函数

    • 1 个回答
  • Marko Smith

    我使用 django 管理面板添加图像,但它没有显示

    • 1 个回答
  • Marko Smith

    这些条目是什么意思,它们的完整等效项是什么样的

    • 2 个回答
  • Marko Smith

    浏览器仍然缓存文件数据

    • 1 个回答
  • Marko Smith

    在 Excel VBA 中激活工作表的问题

    • 3 个回答
  • Marko Smith

    为什么内置类型中包含复数而小数不包含?

    • 2 个回答
  • Marko Smith

    获得唯一途径

    • 3 个回答
  • Marko Smith

    告诉我一个像幻灯片一样创建滚动的库

    • 1 个回答
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Алексей Шиманский 如何以及通过什么方式来查找 Javascript 代码中的错误? 2020-08-03 00:21:37 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    user207618 Codegolf——组合选择算法的实现 2020-10-23 18:46:29 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5