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!
-
1
You are immediately executing
MyFunction
, replaceMyFunction()
withMyFunction
– 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
3 Answers
Reset to default 7You'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条)