单击按钮调用javascript函数时没有任何反应

时间:2014-01-05 16:58:07

标签: javascript function onclick

以下代码应显示确认框。如果用户单击确定按钮,则应显示当前时间。但由于某种原因,当我通过点击它测试按钮时没有任何反应。我需要一双新鲜的眼睛来告诉我,为什么这段代码不能正常工作,我错过了什么。谢谢你的帮助:

<script>
function confirmationDemo() {
    var ok = confirm("Click OK to show the time, \n or click Cancel to close this window \n         
without doing anything.");
    var now = new Date();
    var hour;
    var minute;
    if (now.getHours() < 12) {
        hour = now.getHours();
    } else {
        hour = now.getHours() - 12;
    }
    if (now.getMinutes() < 10) {
        minute = "0" + now.getMinutes();
    } else {
        minute = now.getMinutes();
    }
    if (ok == true && now.getHours() < 12) {
        document.getElementById("confirmationDemoReturn").innerHTML = "The time is: " + hour +
            ":" + minute + " am.";
    } else {
        document.getElementById("confirmationDemoReturn").innerHTML = "The time is: " + hour +
            ":" + minute + " pm.";
    }
}
</script>

Try it: &nbsp; <input type="button" value = "Confirmation Box" onClick =   
"confirmationDemo();">
<p id="confirmationDemoReturn"></p>

2 个答案:

答案 0 :(得分:1)

问题似乎太简单了,确认中的文字没有正确连接。因此它没有用。

 var ok = confirm("Click OK to show the time, \n or click Cancel to close this window \n   
//--- an enter key is pressed     
without doing anything.");

我已经在fiddle

进行了测试

答案 1 :(得分:0)

首先,您不应该在HTML中设置事件,而应该在JS中设置事件。 HTML用于结构,而不用于交互。但是,如果要使用此方法,则必须在文档的标题中添加以下元标记:

<meta http-equiv="Content-Script-Type" content="text/javascript">

但是,我建议在JavaScript中添加事件,如下所示:

var button = document.getElementById('btn');
button.onclick = confirmationDemo;

当然在为您的输入设置了ID后:

<p id="confirmationDemoReturn"></p>

查看这个小提琴:http://jsfiddle.net/R5t6z/

相关问题