简体   繁体   English

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

[英]Why my javascript file doesn't load?

This is the code of my html file: 这是我的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>

And this is the code of my javascript file: 这是我的javascript文件的代码:

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

Because the element doesn't exist yet. 因为该元素尚不存在。 Try putting the javascript at the end of the body 尝试将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>

It seems to work just fine when inlining. 内联时似乎工作得很好。

 <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> 

The usual way to do this is to wrap your javascript in jquery's document ready function like this. 通常的方法是将JavaScript封装在jquery的document ready函数中,如下所示。 If you're not using jquery, you should check it out, it's really useful. 如果您不使用jquery,则应将其签出,这确实很有用。

$( document ).ready(function() {
    console.log( "ready!" );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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