简体   繁体   中英

how to get value from other script? (in html)

I want to get value from other script.

(about socket.io) A script -> (about highchart) B script

this is A script

<script>
var socket = io();

socket.on('currTemp', function(data){
    document.getElementById("temp").innerHTML = "Temperature : " + data;
                   ***// I WANT 'data'.***
}); </script>

and this is B script

<script type="text/javascript"> 

....
code
....

setInterval(function () {
var point,
    newVal,
    inc;

if (chartRpm) {
    point = chartRpm.series[0].points[0];
    inc = ------> ***I want 'inc = data '***
    newVal = inc;

    if (newVal < 0 || newVal > 1200) {
        newVal = point.y - inc;
    }

    point.update(newVal);
}}, 2000); </script>

this code is in same file. how to do that ?

You can assign a global variable in one script like this:

window.myVariable = "some_value";

and then access it like you would any other variable in your other script;

Declare a var globally simply with var data; Both scripts should be able to access the variable.

Do check out https://www.w3schools.com/js/js_scope.asp .

You options are:

1- Global Variable: By Assigning window.data = data in A script and use it in B script by using inc = window.data

2- Use global events where A script fires an event with data attached to it and it will caught by B script.

3- Use any JS state management lib to share data between "components"

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