最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change html content, when the page has fully loaded - Stack Overflow

programmeradmin6浏览0评论

So, I have this HTML document

<!DOCTYPE html>
<html>
  <head>
  <title>TestPage</title>
    <script src="script.js"></script>
  </head>
  <body>
    <p id="test">Sample text</p>
  </body>
</html>

With this JS file

window.addEventListener("load", MyFunction());
function MyFunction(){
  document.getElementById("test").innerHTML = "it worked";
}

and ofcourse this doesn't work (the text isn't changed), since it loads the script before it actually loads the <p id="test"></p> element (I think). It may seem strange, but I want to change the content of some elements, after everything has loaded. I have searched, but to no avail. I'm missing something obvious here probably, but I can't seem to figure it out. Any advice would be appreciated!

So, I have this HTML document

<!DOCTYPE html>
<html>
  <head>
  <title>TestPage</title>
    <script src="script.js"></script>
  </head>
  <body>
    <p id="test">Sample text</p>
  </body>
</html>

With this JS file

window.addEventListener("load", MyFunction());
function MyFunction(){
  document.getElementById("test").innerHTML = "it worked";
}

and ofcourse this doesn't work (the text isn't changed), since it loads the script before it actually loads the <p id="test"></p> element (I think). It may seem strange, but I want to change the content of some elements, after everything has loaded. I have searched, but to no avail. I'm missing something obvious here probably, but I can't seem to figure it out. Any advice would be appreciated!

Share Improve this question asked Oct 15, 2015 at 11:55 Spike de HeldSpike de Held 871 silver badge6 bronze badges 2
  • 1 You are immediately executing MyFunction, replace MyFunction() with MyFunction – Yvo Cilon Commented Oct 15, 2015 at 11:57
  • also you shouldn't use a captial letter in My, because these are usually only used for classes (or javascript's weird prototype system) – Florian Wendelborn Commented Oct 15, 2015 at 12:02
Add a ment  | 

3 Answers 3

Reset to default 7

You're calling the function in the setup for your "load" event.

Did you mean:

window.addEventListener("load", MyFunction);

??

Try:

window.onload = function () { 
    MyFunction() 
}

function MyFunction(){
    document.getElementById("test").innerHTML = "it worked";
}

Source: Execute Javascript When Page Has Fully Loaded

Simply add this to your body tag :

<body onload=myFunction()>

function myFunction(){
      document.getElementById("test").innerHTML = "it worked";
}
发布评论

评论列表(0)

  1. 暂无评论