简体   繁体   中英

Javascript in an external file

Before I ask this question I must point out that I have tried to search for EVERYTHING!

My question is how can I run javascript from an external file instead of inside my php / html. What I'm trying to do is.

    function ClearForm() {
      document.form.message.value="";
    }

    function comeBack(){
      if (document.form.message.value == "") {
         document.form.message.value="What's on your mind?";
      }      
    }

I have included <script type="text/javascript" src="javascript.js"></script> in the <head> and I have a file in the root called javascript.js and my php file is in the root too so that shouldn't be the problem! But how do I run that pieces of code you see above in the javascript.js file instead of in my php file. It work's fine if I have it in the php file but I want to separate things!

I have also tried to give the form / input field an id and then use getElementById in the external JavaScript file.

But as you can see and hear I'm kinda new to JavaScript so I'm apparently doing something wrong here.

If the above code is the only thing in your Javascript.js file, then you need to call the functions to run the code.

You've included the external Javascript file correctly - however, because all of your JS is included within functions, these function/s must be called before the code will run.

A call to 'ClearForm()' or 'comeBack()' from within your PHP file should run the code.

That JS file will have to be in the same folder as your PHP page.

Test whether the file is found or not by adding this line at the top of the js file

alert('js file found OK!');

document.form is an array, so if you only have one form use:

document.forms[0]

Also depending on which browser you use, find and install some Developer Tools to help you identify these errors.

You have declared those functions in the <head>. All fine.

The question is when do you want to call/run those functions?

If you simply want to run them at the end of the page, then you can add another external javascript file and include it using <script src="my_external_file.js"> right before the </body> tag.

Otherwise, you have to declare onXXX handlers, like onLoad() for the document, onClick() for certain elements, onSubmit() for forms, etc. These, too, can be declared in an external file, but specified after the relevant elements are loaded.

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