按钮点击后显示倒数计时器

时间:2015-09-07 13:09:34

标签: javascript timer countdown countdowntimer

我有一个包含许多行的表(最后约为50 - 100),每行都有不同的超时。我想点击第一个按钮(链接)第一行开始的倒计时,如果在第二行,第二个倒计时开始。

倒计时结束后,将显示任何单词而不是计时器。

以下是两行例句:

<tr>
      <td><form action="http://www.google.fr"><input type="submit" formtarget="_blank" value="Google 3 seconds"></form>
      </td>
      <td>00:00:03</td>
</tr>
<tr>
      <td><form action="http://www.google.fr"><input type="submit" formtarget="_blank" value="Google 2h30mins"></form>
      </td>
      <td>02:30:00</td>
</tr>

对于js,我在这里找到了这个:http://jsfiddle.net/6nDYd/10/

任何人都可以帮我用我提供的链接创建js脚本吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

来自SO

的参考号

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}

function startTimer() {
  var nextElem = $(this).parents('td').next();
  var duration = nextElem.text();
  var a = duration.split(':');
  var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
  setInterval(function() {
    seconds--;
    if (seconds >= 0) {
      nextElem.html(toTimeString(seconds));
    }
    if (seconds === 0) {
      alert('sorry, out of time');
      clearInterval(seconds);
    }
  }, 1000);
}
$('.btn').on('click', startTimer);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <form action="http://www.google.fr">
        <input class="btn" type="button" formtarget="_blank" value="Google 3 seconds">
      </form>
    </td>
    <td>00:00:03</td>
  </tr>
  <tr>
    <td>
      <form action="http://www.google.fr">
        <input class="btn" type="button" formtarget="_blank" value="Google 2h30mins">
      </form>
    </td>
    <td>02:30:00</td>
  </tr>
</table>

答案 1 :(得分:1)

刷新并关闭浏览器后如何继续计时器?

&#13;
&#13;
function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}

function startTimer() {
  var nextElem = $(this).parents('td').next();
  var duration = nextElem.text();
  var a = duration.split(':');
  var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
  setInterval(function() {
    seconds--;
    if (seconds >= 0) {
      nextElem.html(toTimeString(seconds));
    }
    if (seconds === 0) {
      alert('sorry, out of time');
      clearInterval(seconds);
    }
  }, 1000);
}
$('.btn').on('click', startTimer);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <form action="http://www.google.fr">
        <input class="btn" type="button" formtarget="_blank" value="Google 3 seconds">
      </form>
    </td>
    <td>00:00:03</td>
  </tr>
  <tr>
    <td>
      <form action="http://www.google.fr">
        <input class="btn" type="button" formtarget="_blank" value="Google 2h30mins">
      </form>
    </td>
    <td>02:30:00</td>
  </tr>
</table>
&#13;
&#13;
&#13;