代码之家  ›  专栏  ›  技术社区  ›  xiaolingxiao

导航到页面后运行javascript

  •  3
  • xiaolingxiao  · 技术社区  · 7 年前

    我在一些 pug 文件:

    doctype html
    html
        //- this is not firing for some reason
        head
    
            script(type="text/javascript").
              document.addEventListener('DOMContentLoaded', function() {
                  console.log('ready!')
             }, false);
    

    脚本仅在刷新页面时运行,而不是在导航到脚本未触发的页面时运行。我在找一个像这样的活动 onNavigate ,但我在这里的列表中没有看到: https://www.w3schools.com/jsref/dom_obj_event.asp 或此处: https://developer.mozilla.org/en-US/docs/Web/Events

    2 回复  |  直到 7 年前
        1
  •  2
  •   Johnsackson    7 年前

    您的代码应该可以正常工作(如果您的代码是以这种方式编写的)。没有问题。

    <!doctype html>
       <html>
        <body>
          <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {
               console.log('ready!')
            }, false);
          </script>
        </body>
       </html>
    

    <!doctype html>
    <html>
    <body>
    <script type="text/javascript">
      window.onload = function() {
        console.log('ready!')
      };
    </script>
    </body>
    </html>
    
        2
  •  2
  •   rockmo    7 年前

    您知道发生车身过载事件 之后 任何css和js加载-包括外部引用。

    您真正需要的是:

    <body onload="do_this()">
    

    然后在script元素中

    function do_this(){
    //  do sh1t
    }