javascript 按按钮启动和停止简单时钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12985893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:33:50  来源:igfitidea点击:

Start and stop simple clock on button push

javascriptjqueryhtml

提问by

I have a simple webpage:

我有一个简单的网页:

<html>
  <body>
    When button has value of "Start Clock" and button is pushed:
      <li>The clock information is shown in the textfield</li>
      <li>The value of the button changes to "Stop Clock"</li>
    When the button has the value "Stop Clock" and button is pushed
      <li>The clock information stops in the textfied</li>
      <li>The button value changes to "Start Clock"</li>

    <input type="text" id="clocktext"/>
    <input type="button" id="clockb" value="Start Clock"/> 

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="scripts.js"></script>
  </body>
</html>

I also have a script file:

我还有一个脚本文件:

function myclock() { 
    var date = new Date(); // Get the current date/time
    var hour = date.getHours(); // Save hours
    var min = date.getMinutes(); // Save minutes
    var sec = date.getSeconds(); // Save seconds
    formathour = format(hour); // Format hours
    formatmin = format(min); // Format minutes
    formatsec = format(sec); // Format seconds
    timeout = setTimeout("myclock()", 1000); 
}

function format(x) {
    if (x < 10) x = "0" + x;
    return x;
}

$("#clockb").click(function () {
    var c = setInterval(setTheTime(), 1000);
    if (this.value == "Start Clock") {
        $(this).prop('value', 'Stop Clock'); // Set button value to Stop Clock
    } else if (this.value == "Stop Clock") {
        $(this).prop('value', 'Start Clock');
            clearInterval(c);
    }
});

function setTheTime() {
    myclock();
    var curTime = formathour+":"+formatmin+":"+formatsec // Current time formatted
    $("#clocktext").prop('value', curTime);
}

I cannot get the clock to continually update when the button is pushed :/

按下按钮时,我无法让时钟持续更新:/

I feel like I'm over complicating this and its very annoying.

我觉得我把这件事复杂化了,这很烦人。

Any insight would be helpful as I am very new to jQuery and js

任何见解都会有所帮助,因为我对 jQuery 和 js 非常陌生

采纳答案by dfsq

Here is working code: http://jsfiddle.net/hUYZv/1/

这是工作代码:http: //jsfiddle.net/hUYZv/1/

Your error was in incorrect usage of setInterval. It should be:

您的错误在于 setInterval 的使用不正确。它应该是:

var c = setInterval(setTheTime, 1000);

You want to provide a refference to the function not the result of its execution (as would be if you write setTheTime());

您想提供对函数的引用,而不是其执行结果(就像您编写的那样setTheTime());

回答by polin

you can use this.click on the span

你可以使用 this.click 在跨度上

<span id="clock" style="background-color:#9CC;float:right" onclick="updateClock();">&nbsp;</span>
<script type="text/javascript">

function updateClock ( )
{
var currentTime = new Date ( );

var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );

// Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

  // Choose either "AM" or "PM" as appropriate
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

  // Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

// Convert an hours component of "0" to "12"
//currentHours = ( currentHours == 0 ) ? 12 : currentHours;

// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " "   + timeOfDay;

// Update the time display
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
</script>

回答by alestanis

I think you're missing one of two things:

我认为你错过了两件事之一:

  • Either you didn't include the jquery lib inside your html file
  • Either you didn't put your function inside a document.ready.
  • 要么你没有在你的 html 文件中包含 jquery lib
  • 要么你没有把你的函数放在 document.ready 中。

You should wrap two of your functions like this:

您应该像这样包装两个函数:

$(document).ready(function() {
function setTheTime() {
    myclock();
    var curTime = formathour+":"+formatmin+":"+formatsec // Current time formatted
    $("#clocktext").prop('value', curTime);
}

$("#clockb").attr("onclick", "").click(function () {
    var c = setInterval(setTheTime(), 1000);
    if (this.value == "Start Clock") {
        $(this).prop('value', 'Stop Clock'); // Set button value to Stop Clock
    } else if (this.value == "Stop Clock") {
        $(this).prop('value', 'Start Clock');
            clearInterval(c);
    }
});

You can see a working code here: http://jsfiddle.net/T47ME/

你可以在这里看到一个工作代码:http: //jsfiddle.net/T47ME/