简体   繁体   中英

Javascript file will not load

I have a simple script that works when included in the html body. However, when running this from a relative path, and including the

<script type="text/javascript" src="simple.js"></script>

in either the header or bottom of the html file, the script will no longer run.

Can anyone point as to what I am missing ?

Thank you.

Script simple.js:

<script>
        function firstFunction(){

            var a = document.getElementById("firstInput").value;

            if(! a){
                alert("minimum input of 1 char required");
            }else{
                document.getElementById("firstOutput").innerHTML=a;
            }


        }

        function secondFunction(){
            var b = document.getElementById("secondInput").value;

            if(!b){
                alert("minimum input of 1 char required");
            }


            document.getElementById("secondOutput").innerHTML=b;
            //document.getElementById("secondOutput").innerHTML = "updated!";
        }

You only need the <script> tag if you include the javascript into your html file.

In a .js file, it's a syntax error. Just write your javascript code without the tag!

File simple.js:

function firstFunction(){

        var a = document.getElementById("firstInput").value;

        if(!a){
            alert("minimum input of 1 char required");
        }else{
            document.getElementById("firstOutput").innerHTML=a;
        }


    }

    function secondFunction(){
        var b = document.getElementById("secondInput").value;

        if(!b){
            alert("minimum input of 1 char required");
        }


        document.getElementById("secondOutput").innerHTML=b;
        //document.getElementById("secondOutput").innerHTML = "updated!";
    }

As your file is right now, make sure to place the script right before the closing body tag

<script type="text/javascript" src="simple.js"></script>
</body>

so that the elements can be found when the script is running.

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