toggle javascript function

2019-07-19 02:35发布

I'm using this code to start a log file :

function startTail(str) {
if (str== "stop") {
stopTail();
} else {
t= setTimeout("getLog()",1000);
}
}

This is called using :

<button id="start" onclick="getLog('start');">

and stopped using :

<button id="stop" onclick="getLog('stop');">

Is there anyway I can change this to one button that will toggle start / stop ?

2条回答
放荡不羁爱自由
2楼-- · 2019-07-19 03:00

Try:

<button id="start" value="Toggle Log" onclick="getLog('start', this);">

function startTail(str, element) {
    if (str == "stop") {
        stopTail();
        element.setAttribute('onclick', "getLog('start', this);");
    } else {
        element.setAttribute('onclick', "getLog('stop', this);");
    }
}   
查看更多
贪生不怕死
3楼-- · 2019-07-19 03:23

You could try this

var flag = false;
function startTail() {
 if (flag)
  {
    stopTail();
    document.getElementById('start').value = "Start";
    flag = false;
  }
 else 
  {
    t= setTimeout("getLog()",1000);
    flag = true;
    document.getElementById('start').value = "Stop";
  }
}

<button id="start" onclick="startTail();" value="Start">
查看更多
登录 后发表回答