Access js variable of one file in another file using JQuery

后端 未结 2 763
遇见更好的自我
遇见更好的自我 2021-01-16 13:59

I have 2 js files: 1.js and 2.js.
In 1.js I have a variable

var test =\'Hello\';

I\'m trying to access the variable in 2.js

<         


        
2条回答
  •  野的像风
    2021-01-16 14:50

    Make sure your var test is not inside a function and that your file is load in the correct order. In your first file use something like

    
    // Now here include your js file too JS file 
    // Or set in window scope like window.test="myVar";
    

    And in your JS file use like

    $(function() {
      alert(test);
      // alert(window.test);
    });
    

    A variable in global scope can be access from all javascript file. Your first js file

    Here is another way.

    //first.js file don't put variable inside any function here.
    var globalVariable={
       test: 'myVar'
    };
    

    And your second js file

    //second.js file
    alert(globalVariable.test);
    

    And in html page add

     
     
    

    More from here

提交回复
热议问题