试图在div中显示当前时间

时间:2015-04-02 20:25:06

标签: javascript php html

当单击各个按钮时,

wave time in和timeout应该保持当前时间的值。但点击唯一的闪光灯消失

<!DOCTYPE html>

<html>
<head><title></title>
<script>
function inTime(){
 var time = document.getElementById("timein").innerHTML = 
 "<?php echo date('h:i:sa'); ?>";
 return time;
}

function outTime(){
var time = document.getElementById("timeout").innerHTML = 
"<?php echo date('h:i:sa'); ?>";
return time;
}

</script>
</head>
<body>

<form action="time.php">
<fieldset>
<legend>Time Log</legend>
<p>Time In: <div id="timein" value=""></div></p><br>
<button id="submitIn" name="submitIn" onclick = 
"inTime()">Time In</button>
<p>Time Out: <div id="timeout" value=""></div></p><br>
<button id="submitOut" name="submitOut" onclick = 
"outTime()">Time Out</button>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您可能正在提交表单

<button id="submitIn" name="submitIn" onclick="inTime()">Time In</button>

如果没有type声明,您的浏览器会假设此按钮的功能是提交表单。因此,即使您的JS甚至触发,您也会强制页面重新加载。将它们声明为按钮只能修复

<button type="button" id="submitIn" name="submitIn" onclick="inTime()">Time In</button>

答案 1 :(得分:0)

您的功能可以简化,您可以在按钮上return false;以防止它在您明确调用的脚本之外执行任何操作。

更新(根据原始海报的用例详情进一步更改):

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <form action="time.php">
            <fieldset>
                <legend>Time Log</legend>
                <div>
                    <label labelfor="timeIn">Time In: </label>
                    <span id="timeIn" value=""></span>
                    <br />
                    <button id="timeInButton" onclick="getTime('timeIn');return false;">
                        Clock In
                    </button>
                </div>
                <br />
                <div>
                    <label labelfor="timeOut">Time Out: </label>
                    <span id="timeOut" value=""></span>
                    <br />
                    <button id="timeOutButton" onclick="getTime('timeOut');return false;">
                        Clock Out
                    </button>
                </div>
            </fieldset>
        </form>

        <script type="text/javascript">
            function getTime(element) {
                var currentDate = new Date();
                document.getElementById(element).innerHTML = currentDate.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3");
            }
            getTime('timeIn');   
        </script>
    </body>
</html>