[JavaScript] Why? This simple function doesn't work?

2016-05-02 12:22 am
<!DOCTYPE html>
<html>
<head>

<script>
function myFunction(a, b) {
return a * b;

document.getElementById("demo").innerHTML = myFunction(4, 3);
}
</script>
</head>

<body>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>

</body>
</html>

回答 (3)

2016-05-02 12:43 am
Remove document.getElementById( "demo").innerHTML = myFunction(4, 3)

After <p id="demo"></p>, insert

<script>
document.getElementById( "demo").innerHTML = myFunction(4, 3)
</script>

Or use this method —

<head>
<script defer>
function calcDemo() {
document.getElementById( "demo").innerHTML = myFunction(4, 3)
}
function myFunction(a, b) {
return a * b
}
</script>
</head>
<body onload="calcDemo()">
<p>This example calls a function that performs a calculation, and returns the result:</p>
<p id="demo"></p>
2016-05-02 1:06 am
JavaScript code is run as it's encountered and while it's running it blocks the web page from loading. The paragraph tag hasn't loaded when you call `document.getElementById()` so your code fails. Move your script tag to just before the closing body tag. That way all the HTML elements will have loaded and be available.
2016-05-02 12:37 am
You have to call the function

myFunction(1,2); for example


收錄日期: 2021-04-18 14:47:41
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20160501162218AAxpijO

檢視 Wayback Machine 備份