javascript - 为什么我的 javascript 文件无法加载?

标签 javascript html

这是我的 html 文件的代码:

<html>
    <head>
        <script type="text/javascript" src="try1.js"></script>
    </head>

    <body>

        <h1>A Web Page</h1>
        <p id="demo">A Paragraph</p>
        <button type="button" onclick="myFunction()">Try it</button>

    </body>
</html>

这是我的 javascript 文件的代码:

function myFunction() {
     document.getElementById("demo").innerHTML = "Paragraph changed";
}

最佳答案

因为该元素还不存在。尝试将 javascript 放在正文的末尾

<html>
    <head>
        <title>Example<title>
    </head>
    <body>

        <h1>A Web Page</h1>
        <p id="demo">A Paragraph</p>
        <button type="button" onclick="myFunction()">Try it</button>
        <script type="text/javascript" src="try1.js"></script>
    </body>
</html>

在内联时似乎工作得很好。

   
        <h1>A Web Page</h1>
        <p id="demo">A Paragraph</p>
        <button type="button" onclick="myFunction()">Try it</button>
        <script type="text/javascript">
        function myFunction() {
            document.getElementById("demo").innerHTML = "Paragraph changed";
        }
        </script>

关于javascript - 为什么我的 javascript 文件无法加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44553525/

相关文章:

javascript - 按钮不调用 onClick (html)

javascript - 单击按钮时无法重定向到新 URL

javascript - 有没有办法实现 "click"、 "double click"和 "click and hold"来处理同一元素?

javascript - 为什么 MongoDB 查询使用 $gt 和 $lte 而不是 > 和 <=?

javascript - jQuery 从生成的内容生成内容

javascript - Angular JS : Show/Close div based on select option without using controller or model

javascript - 我正在尝试使用 Javascript 处理鼠标悬停事件并遇到一些问题

javascript - Skrollr 背景动画不会交换

javascript - 对使用 SQL Server 数据库的 ASP 站点的攻击

javascript - 如何将ipcMain.on调用移至main.js文件之外