toggle javascript function

…衆ロ難τιáo~ 提交于 2019-12-11 01:24:34

问题


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 ?


回答1:


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);");
    }
}   



回答2:


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">


来源:https://stackoverflow.com/questions/13838064/toggle-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!