简体   繁体   中英

How to call a function from javascript file and save the return value as global

Inside an HTML I have a script:

<script src="info.js" type="text/javascript"></script>

Inside info.js there is a function, lets say getInfo(key) which returns info .

How can I call a function located inside info.js from my html, so that I can use this variable inside the whole html document?

w3schools does not explain how to do this

Something like this:

var global; // global var

// js code...


// function
function myFunc(){
  global = getInfo(key);
}

This might help you understand what's going on.

Let's say the code below is located inside info.js

function getSomething(){
  return "something";
}

Now your HTML might look like this

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="info.js" type="text/javascript"></script>
</head>
<body>

    <span id="mySpan"></span>

    <script>
        var myText = getSomething();

        $('#mySpan').text(myText); //this uses jQuery so you'll need to include that
    </script>
</body>
</html>

If I got you correctly, that you want to use that info in all your html file, here's my answer. Let me know if it helps or if you meant anything else, I'll think accordingly.

<html>
<head>
    <script src="info.js" type="text/javascript"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var info = getInfo(key);
            $('div.myinfo').html(info);
        });
    </script>
</head>
    <div class="myinfo"></div>
</html>

You have the desired information in a javascript var and you can assign it as value to a input/select element or copy it as html to a div/td/p/h1 etc.

像这样使用它:

var info = getInfo(key);

只要您的调用脚本遵循info.js中的方法(并假设该函数不是私有的),它就可以在任何脚本中访问

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