简体   繁体   中英

Adding an external JavaScript file in NetBeans and linking with the index file

I have added a JavaScript file into my existing project and referred that in the HTML file. The file structure is shown as its in the attachment . After I run the program, the output does not display what it is supposed to be. Is there anything wrong with my file tree (how I am adding file into the project) or I am not referring the script the in the correct way? Here is how my program looks like:

index:

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="newjavascript.js" type="text/javascript"></script>
    </head>
    <body>
        <p id="demo"></p>
    </body>
</html>

.JS:

document.getElementById("demo").innerHTML = 7+9;

It seems to be everything is ok with your project structure and refererring to js file inside index.html . However, the demo paragraph does not display what you want because it can be just not loaded in the time when your newjavascript.js is executed. I think you can try to modify it in the following way:

window.onload = function () {
    document.getElementById("demo").innerHTML = 7+9;
};

Using onload function of window object you wait until a page (including demo paragraph) is loaded - and after it change its content.

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