javascript - 我有一个有很多变量的函数。如何在其他功能中使用它们?
问题描述
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()函数中的变量h的值等于setInterval()中的Hours变量,我想在控制台中打印 true 。我怎么做?
解决方案
我不肯定这是你的要求,但我很确定你需要做的就是将变量声明移出函数。
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);
}
}
编辑
如评论中所述,代码存在一些问题,这是我对您的建议。不要在不同的函数中使用重复的标识符名称,因为这可能会使您作为初学者感到困惑。将需要从多个函数访问的所有变量名移动到全局范围。
推荐阅读
- node.js - 我是否应该关注 mongoose/mongodb 及其建立/持有的“连接”数量?
- haskell - 如何从 Haskell 访问 python3.6+?
- excel - excel vba宏在activecell.formula行上停止/调试
- iis - ASP.NET Web API 服务使用的 IIS 线程数
- php - 将用户注册仅限于特定电子邮件地址或特定 GSuite 组?
- javascript - 是否有从标签调用 JS 函数的 Wordpress 方法或插件?
- r - 将多元素字符转换为R中的不同独立元素
- python - 通过 python 脚本缓慢插入,即使只有 400 行
- django - 由于 django.core.exceptions.SuspiciousFileOperation 无法打印图像完整路径
- php - 致命错误:在第 10 行的 /Users/darryljackson/Desktop/CRUD/create.php 中调用 null 上的成员函数 prepare()