简体   繁体   中英

unable to call function to pass variable value from another javascript file

I used a specific question name to avoid duplicate question names, since I found some posters had the same problem and I have used the solutions offered but still unable to call the function from another javascript file and use alert() to see the variable value from another js file passed to html page.

In my file.js file, I have a function to declare an array and put a global variable:

function MsgsArr(){
var Msgs = [
  "Msg1.",
  "Msg2.",
];
return Msgs;
}
var Msgs_Arr = MsgsArr();

followed by a function to create a random message and declare global variable:

function CreateRandomMsg(){
var RandomMsg = Msgs_Arr[Math.floor(Math.random()* Msgs_Arr.length)];
return RandomMsg;
}
var Random_Msg = CreateRandomMsg();

Then it's the final function I want to achieve, to show the value based on the random message:

function ValuesToCheck(){

if (Random_Msg == Msgs_Arr[0] || Random_Msg == Msgs_Arr[1]){
var check = facesDet.photos[0].tags[0].attributes.glasses.value
};
return check;
};

Since in the real case I have more than 2 messages, each 2 messages will share one value, the if statement will thus be longer. In my file1.html file, in a function I want to display the final value (true or false), and I use alert(ValuesToCheck()) to call the function, but it doesn't work. If I declare the value like var a = facesDet.photos[0].tags[0].attributes.glasses.value; in here and alert(a); it will work. I'm not sure why things are not working when I'm trying to call the function from another js file, please help. Sorry the question seems lengthy to read. Thanks for taking your time to read it.

var facesDet = $.getJSON( APIdetect, function(facesDet) {
})

.done(function (facesDet, tid) {
    var tid = facesDet.photos[0].tags[0].tid;
    Load(tid);
    alert(ValuesToCheck());
});

From what I can see is that in your ValueToCheck function, RandomMsg and Msgs are uninitialised. basically they are not global. you need to use Random_Msg and Msgs_Arr instead.

Try this.

function ValuesToCheck(){
   if (Random_Msg1 == Msgs_Arr[0] || Random_Msg2 == Msgs_Arr[1]){
      var check = facesDet.photos[0].tags[0].attributes.glasses.value
   };
   return check;
};

In your js file

var Random_Msg1 = CreateRandomMsg(),
    Random_Msg2 = CreateRandomMsg();

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