简体   繁体   中英

does placing of script tag in html file alter the output?

I tried placing a javascript code in the head tag but the browser didn't give any output but when I placed the script tag under the div I targeted in the function it works perfectly. Why does that happen?

below is the code i tried:

  <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>    
    function myValues(){         
        var i, max = 0;       
            for(i = 0; i < arguments.length; i++){
                if(arguments[i] > max){
                        max = arguments[i];
                        }                                   
        }
        return max;         
    }
     document.getElementById("demo").innerHTML = myValues(1, 5, 0, 55, 78, 8989, 3166);
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>

It wont work in the head tag because the DOM has not loaded yet. It wont know where the demo element is yet.

If you put it on an onload function it would execute after the page has loaded. If you moved it down the page below the main DOM it would work too as its loaded the element before the script is run.

因为脚本立即运行,并且页面尚未创建#demo元素。

You should put your script tag somewhere after your div#demo . because you need it in your script. best place is to put it before </body>

如果将<script>标记放在<div>上方,则脚本运行时该元素将不存在。

Javascript will the script when it appears in the code, so placing it before the HTML you want to change will do nothing as the demo element doesn't exist yet. You should place the script after the html for the demo element

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