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

So, I have this HTML document<!DOCTYPE html><html><head><title>TestPage<ti

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";
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744296157a4567271.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信