检查工作时间

时间:2013-11-07 16:19:38

标签: javascript html

我正在试图弄明白为什么这段代码无法运行。 函数isWorkingHour肯定有效,因为我在这里使用它:Working Hours (Working Demo)

任何人都可以提供帮助。 这是JS代码:

function makecall()
{

if (isWorkingHour(now)) {
    //it's in schedule
    window.alert("Office is open");
    }
    else {
    window.alert("Office is close");    
    }
}


function isWorkingHour(now) {
return now.getDay() <= 4 && now.getHours() >= 9 && now.getHours() < 17;
}

我使用的HTML如下:

<input type="button" id="CallButton" class="callButton" value="Call" onclick="makecall()" />
        <p id="demo">Click the button to check if now is working hours</p>

这是我坚持的JSFiddle。 http://jsfiddle.net/zfSTj/3

3 个答案:

答案 0 :(得分:1)

首先,makecall不是全局函数(它包含在被称为onload的函数中),因此您无法从内部事件属性访问它。

其次,你永远不会定义“现在”。

首先定义now

function makecall() {
    var now = new Date();

然后附加一个事件监听器,而不是使用onclick属性:

document.getElementById('CallButton').addEventListener('click', makecall);

这样:http://jsfiddle.net/zfSTj/8/

答案 1 :(得分:1)

在JSFiddle中非常清楚:now变量未定义。将now替换为new Date()

答案 2 :(得分:1)

makecall = function() {

    if (isWorkingHour(new Date())) {
        //it's in schedule
        document.getElementById("demo").innerHTML = "Office is open";
    } else {
        document.getElementById("demo").innerHTML = "Office is closed";
    }
}

这样做可以使makecall成为一个全局函数,以便您可以在JSFiddle中访问它。

我还继续使用now

替换原始参数中的new Date()(在传递时不存在)