简体   繁体   中英

How to call external js file variable in HTML

I have a js file.

File Name: propoties.js

function simple()
{
    alert("simple");
    var text = "Control";
}

These is my html code. What i want is alert that text variable in html.

<html>
<script type='text/javascript' src='path/propoties.js'></script>    
<script>
    simple();
    alert(text); /* It is not working */
</script>
 </html>

Please help me these. Thank you.

Your js file:

var simple=function(){
   var textMultiple = {
        text1:"text1",
        text2:"text2"
    };
   return textMultiple;
}

In your html:

<html>
    <script type='text/javascript' src='./relative/path/to/propoties.js'></script>    
    <script>
      alert(simple().text1);
      alert(simple().text2);
    </script>
 </html>

here is a plunkr demo.

If you want to alert the text in external file you need to declare the variable as global like below.

var text = "Control";
function simple()
{
    text="Changed";
    alert("simple");   
}

or you can declare the variable using window keyword

function simple()
{
    alert("simple");   
    window.text = "Control";
}

please check in plunker http://plnkr.co/edit/HjkwlcnkPwJZ7yyo55q6?p=preview

like you did it the "text" variable is only set in the scope of the function "simple" .

you should make the "text" variable global by declaring it outside the function.

var text = "";

function simple()
{
    alert("simple");
    text = "Control";
}

Declaring the variable globally will work. ie

var text = "";
function simple()
{
     text = "Control";
}

see plunker

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