简体   繁体   中英

Javascript in separate file not working

I'm just starting out in Javascript, and I'm trying to put my scripts in a separate file. They work just fine when they're in the html file, but as soon as I move them to their own separate file it stops working.

Here's my html file:

    <!DOCTYPE html>
<head>
    <meta lang = "en">

    <link rel="stylesheet" type="text/css" href="css/mainStyle.css">
    <script src="js/script1.js"></script>

    <title>Web Dev Practice</title>
</head>

<body>
        <h1>First JavaScript Example</h1>

        <button type="button" onclick="changeText()">ClickMe!</button>

        <p id="demo">This is just a test.</p>

    </br>
    </br>

        <h1>Second JavaScript Example</h1>

        <img id="lightBulb" onclick="changeImage()" src="res/img/pic_bulboff.gif" width="100" height="180">

        <p>Click the light bulb to turn it on or off.</p>

</body>
</html>

And here's my js file:

    <script>
function changeText(){
    var string_first = "This is just a test.";
    var string_second = "Woah, it actually works!";

    if(document.getElementById("demo").innerHTML == string_first){
        document.getElementById("demo").innerHTML = string_second;
    } else{
        document.getElementById("demo").innerHTML = string_first;
    }

}

    <script>
function changeImage(){
    var image = document.getElementById('lightBulb');
        if(image.src.match("bulbon")){
            image.src = "res/img/pic_bulboff.gif";
        }
        else{
            image.src = "res/img/pic_bulbon.gif";
        }
}
 </script>

The <script> tags are html things, not javascript, so you don't need (and can't have) them in your external files. What browser are you using? Many have a built in console that can help you see what errors, if any, your page is throwing.

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