简体   繁体   中英

How do I merge these two button functions into one, like an on/off switch

How can I merge these two button functions into one, so that the button will toggle from isRunning=true to isRunning=false, back again and so forth? "isRunning" is a variable in a javascript function on the page.

Also I would like to replace the standard button into an image button that I design myself (simple .jpg file). Can anyone help? See the code below:

<button onclick="isRunning = false">hold</button>
<button onclick="isRunning = true">continue</button>

There you go:

<button onclick="isRunning = !isRunning; this.innerHTML = (isRunning) ? 'hold' : 'continue'">hold</button>

For your image attempt:

<img src="hold.jpg" onclick="isRunning = !isRunning; this.src = (isRunning) ? 'hold.jpg' : 'continue.jpg'" />
<button onclick="toggleButton(this)">Toggel Me</button>

Then

function toggleButton(element) {
    if(isRunning == false) {
        element.innerHTML = "TRUE";
        isRunning = true;
    } else {
        element.innerHTML = "FALSE";
        isRunning = false;
    }
}

Or even smaller:

<button onclick="toggleButton()">hold</button>

JS:

function toggleButton() {
    isRunning = !isRunning;
}

Though you should consider not using "onclick" and instead registering a proper event handler, as suggested in this MDN article . It allows you to separate your code from the HTML, making it easier to maintain and read. Especially when it's more than just one line of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM