Methods for calling variables and functions across pages in JS (e.g. A.js and b.js) _javascript tips

Source: Internet
Author: User

In the course of project development, you may encounter such a situation.

In a JS file needs to complete a function, but this function of most of the code in another JS file has been completed, they only need to call this method plus a few words of code can achieve the required functionality.

We know that in HTML, the use of <script language= "JavaScript" type= "Text/javascript" src= "./script.js" ></script> The introduction of two JS is not allowed to call each other. So how to solve it? Of course, you can copy the code all over, maybe you don't like it.

For example, there is an HTML, which has a button that invokes method B () in the B.js file when pressed. The method A () in the A.js file is also called in B (). To implement this feature, it is important to note that the JS file code that will be introduced is placed under </body>.

First, we introduce b.js in HTML and add Reference statements after </body>. As follows:

 
 

B.js files are as follows:

New_element=document.createelement ("script"); 
New_element.setattribute ("type", "Text/javascript"); 
New_element.setattribute ("src", "a.js");//introduced here the A.js 
document.body.appendChild (new_element); 
Function B () { 
a (); 
}

In the first 4 lines of code in the B.js file, we introduced the A.js file and called the A () method in the A.js code in the 7th line of code.

Let's analyze the key code: first, we use Document.createelement ("script") to generate a script label, set its Type property to Text/javascript,src as A.js ( The a.js are placed in the same directory as B.js, and can be placed in different directories. Finally, the tag is dynamically added to the body. In this way, we can call to different JS files in the method.

The above is small series for everyone to bring the JS in the cross page call variables and functions of the method (such as A.js and b.js each other) all content, I hope that we support cloud Habitat Community ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.