[英]I have nested Json data stored in variables how do I access them in another function in jquery?
[英]I have a function with many variables. How do I use them in another function?
var min = document.getElementById("minutes");
var sec = document.getElementById("second");
//sets a time interval to repeat.
setInterval(() => { //function() is the same as () => {} or () =>
let d = new Date(); //creating a variable to get the Time
let h = d.getHours(); //creating a variable to get hours and so on..
let m = d.getMinutes();
let s = d.getSeconds();
var Hours = 30*h+m/2+s/120;//calculating
var Minutes = 6*m+s/10;
var Seconds = 6*s;
hou.style.transform = `rotate(${Hours}deg)`;
min.style.transform = `rotate(${Minutes}deg)`;
sec.style.transform = `rotate(${Seconds}deg)`;
},1000)
function setAlarm(){
let h = document.getElementById("h");
let m = document.getElementById("m");
let s = document.getElementById("s");
if (h.innerHTML==Hours){
console.log(true);
}
}
如果 setAlarm () function 中的變量h的值等於setInterval()中的Hours變量,我想在控制台中打印 true 。 我怎么做?
我不肯定這是你的要求,但我很確定你需要做的就是將變量聲明移出 function 之類的。
var min = document.getElementById("minutes");
var sec = document.getElementById("second");
let Hours;
//sets a time interval to repeat.
setInterval(() => { //function() is the same as () => {} or () =>
let d = new Date(); //creating a variable to get the Time
let h = d.getHours(); //creating a variable to get hours and so on..
let m = d.getMinutes();
let s = d.getSeconds();
Hours = 30*h+m/2+s/120;//calculating
var Minutes = 6*m+s/10;
var Seconds = 6*s;
hou.style.transform = `rotate(${Hours}deg)`;
min.style.transform = `rotate(${Minutes}deg)`;
sec.style.transform = `rotate(${Seconds}deg)`;
},1000)
function setAlarm(){
let h = document.getElementById("h");
let m = document.getElementById("m");
let s = document.getElementById("s");
if (h=Hours){
console.log(true);
}
}
如評論中所述,代碼存在一些問題,這是我對您的建議。 不要在不同的函數中使用重復的標識符名稱,因為這可能會使您作為初學者感到困惑。 將需要從多個函數訪問的所有變量名稱移動到全局 scope。
不,但是您可以將變量公開給上 scope 或僅在 setInterval 中調用 setAlarm function。
var min = document.getElementById("minutes");
var sec = document.getElementById("second");
//sets a time interval to repeat.
setInterval(() => { //function() is the same as () => {} or () =>
let d = new Date(); //creating a variable to get the Time
let h = d.getHours(); //creating a variable to get hours and so on..
let m = d.getMinutes();
let s = d.getSeconds();
var Hours = 30*h+m/2+s/120;//calculating
var Minutes = 6*m+s/10;
var Seconds = 6*s;
hou.style.transform = `rotate(${Hours}deg)`;
min.style.transform = `rotate(${Minutes}deg)`;
sec.style.transform = `rotate(${Seconds}deg)`;
setAlarm(Hours);
},1000)
function setAlarm(Hours){
let h = document.getElementById("h");
let m = document.getElementById("m");
let s = document.getElementById("s");
if (h == Hours){
console.log(true);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.