按钮onclick执行多个操作

时间:2014-03-07 12:34:21

标签: javascript jquery function if-statement onclick

我有这段代码:

var hour = parseInt(js_arr[j].substring(0, 1));
var min = parseInt(js_arr[j].substring(3, 4));
var seconds = parseInt(js_arr[j].substring(6, 7));
var mil_sec = parseInt(js_arr[j].substring(9, 11));
var time = (hour * 3600000) + (min * 60000) + (seconds * 1000) + mil_sec;

function timeout() {
    setTimeout(function () {

        if (true) {
            document.getElementById('subs').innerHTML = js_arr[i];
            i = i + 4;
            j = j + 4;
            hour = parseInt(js_arr[j].substring(0, 1));
            min = parseInt(js_arr[j].substring(3, 4));
            seconds = parseInt(js_arr[j].substring(6, 7));
            mil_sec = parseInt(js_arr[j].substring(9, 11));
            time = (hour * 3600000) + (min * 60000) + (seconds * 1000) + mil_sec;

            timeout();
        } else {
            timeout();
        }

    }, time);
}

在javascript代码之前,我有一个onclick="timeout();按钮。

此按钮允许播放字幕。我还希望它能够通过点击相同的按钮来停止播放这些字幕。如果有人能帮忙的话会很棒!

非常感谢。

1 个答案:

答案 0 :(得分:0)

添加一个变量,指示超时是否处于活动状态。在timeout() - 函数中,检查此变量,并且只有在其为真时才启动另一个循环。要启动和停止,只需设置(并调用timeout())或重置变量。

var hour = parseInt(js_arr[j].substring(0,1));
var min = parseInt(js_arr[j].substring(3,4));
var seconds = parseInt(js_arr[j].substring(6,7));
var mil_sec = parseInt(js_arr[j].substring(9,11));
var time = (hour*3600000)+(min*60000)+(seconds*1000)+mil_sec;

var timeOutRunning = false;

function startTimeOut() {
  timeOutRunning = true;
  timeout();
}

function stopTimeOut() {
  timeOutRunning = false;
}

function timeout() {
  if(timeOutRunning) {
    setTimeout(function() {
      document.getElementById('subs').innerHTML = js_arr[i];
      i=i+4;
      j=j+4;
      hour = parseInt(js_arr[j].substring(0,1));
      min = parseInt(js_arr[j].substring(3,4));
      seconds = parseInt(js_arr[j].substring(6,7));
      mil_sec = parseInt(js_arr[j].substring(9,11));
      time = (hour*3600000)+(min*60000)+(seconds*1000)+mil_sec;

      timeout();
    }, time);
  }
}

然后是onclick-function:

onclick="if(timeOutRunning) { stopTimeOut(); } else { startTimeOut(); }"