首页 > 解决方案 > 我有一个有很多变量的函数。如何在其他功能中使用它们?

问题描述

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 。我怎么做?

标签: javascripthtmltypescriptfunctionvariables

解决方案


我不肯定这是你的要求,但我很确定你需要做的就是将变量声明移出函数。

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);
    }
}

编辑

如评论中所述,代码存在一些问题,这是我对您的建议。不要在不同的函数中使用重复的标识符名称,因为这可能会使您作为初学者感到困惑。将需要从多个函数访问的所有变量名移动到全局范围。


推荐阅读