将脚本添加到加载身体后运行的头部

时间:2019-02-24 19:31:53

标签: javascript html

如何在myFunction()中添加head,该操作仅在加载body之后运行。我希望将其包含在head中的原因是因为这样,我可以将其放置在一个文件中,而不是多个文件中。

目前,我有<body onload="myFunction()"></body>可以正常工作。但这需要添加到多个文件中。

示例

<head>
  <style>
    .codetext {
      font-family: monospace;
    }
  </style>

  <script>
    myFunction = function () {
      let links = document.querySelectorAll("a");
      links.forEach(elem => elem.classList.add("codetext"));
    }
	document.body.onload("myFunction"); <!--Doesn't Work-->
  </script>
</head>

<body>
  <a href="">Click Here</a>
</body>

5 个答案:

答案 0 :(得分:2)

您可以使用全局load事件

<script>
  onload = _ => 
    document.querySelectorAll("a").forEach(elem => elem.classList.add("codetext"))
</script>

答案 1 :(得分:1)

使用document.body.onload = handler。参见this answer for more details

<head>
  <style>
    .codetext {
      font-family: monospace;
    }
  </style>

  <script>
    document.body.onload = () => {
      const links = document.querySelectorAll('a');
      links.forEach(elem => elem.classList.add('codetext'));
    }
  </script>
</head>

<body>
  <a href="">Click Here</a>
</body>

或者您可以使用window.onload = handler

答案 2 :(得分:1)

您可以使用

 document.querySelector('body').onload

<head>
  <style>
    .codetext {
      font-family: monospace;
    }
  </style>

  <script>
    document.querySelector('body').onload= function myFunction() {
      let links = document.querySelectorAll("a");
      links.forEach(elem => elem.classList.add("codetext"));
    }
	//document.body.onload("myFunction"); <!--Doesn't Work-->
  </script>
</head>

<body>
  <a href="">Click Here</a>
</body>

答案 3 :(得分:1)

  

TypeError:document.body.onload不是函数

您需要将功能分配给onloaddocument.body.onload = myFunction;

<head>
  <style>
    .codetext {
      font-family: monospace;
      color: red;
    }
  </style>

  <script>
    myFunction = function() {
      let links = document.querySelectorAll("a");
      links.forEach(elem => elem.classList.add("codetext"));
    }
    document.body.onload = myFunction;
  </script>
</head>

<body>
  <a href="">Click Here</a>
</body>

答案 4 :(得分:0)

使用

document.body.addEventListener("load",functionToAssingn)

添加onLoad事件:

<head>
  <style>
    .codetext {
      font-family: monospace;
    }
  </style>

  <script>document.body.addEventListener("load",myFunction)
    myFunction = function () {
      let links = document.querySelectorAll("a");
      links.forEach(elem => elem.classList.add("codetext"));
    }
  </script>
</head>

<body>
  <a href="">Click Here</a>
</body>