简体   繁体   中英

JavaScript won't work if placed inside the body of a web page?

I'm new to JavaScript and I've learned that JavaScript can be place between the <head></head> or <body></body> sections, I have been working in a project and it works fine inside the head but not the body section of the page.

examples:

working fine like this:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Example Page</title>

<script>
function yetAnotherAlert(textToAlert) {
  alert(textToAlert);
}

yetAnotherAlert("Hello World");

And is not working this way:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Example Page</title>



</head>

<body>
 <script>
    function yetAnotherAlert(textToAlert) {
      alert(textToAlert);
    }

    yetAnotherAlert("Hello World");

</script>
</body>

</html>

Your code snippet didn't show you closing the tag. Double check if you close your script block correctly.

It's also better to specify the type of scripting language too.

<script language='javascript'>

....

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM