如何获得一个按钮来执行两个功能

How to get one button to do two functions

本文关键字:执行 两个 功能 一个 何获得 按钮      更新时间:2023-09-26

目前我有两个按钮,一个按钮将文本更改为红色(默认),另一个在单击时将其更改为绿色。而不是有两个按钮,当文本显示为红色时,我需要一个按钮说绿色,所以当你单击绿色按钮时,它会将颜色更改为绿色,然后同一个按钮现在说红色,单击时它会将文本更改为红色

这是我的脚本:

function change1() { 
 txt = document.getElementById("txt");
 txt.style.color = 'green';
}
    function change2() { 
    txt = document.getElementById("txt");
    txt.style.color = 'red';
}

这些是我的按钮

<input type="button" value="Green" onclick="change1()" id="btn">
<input type="button" value="Red" onclick="change2()" id="btn">
你可以

用一个 if 语句来要求style.color属性:

function change() { 
  txt = document.getElementById("txt");
  if (txt.style.color === 'green'){
        txt.style.color = 'red';
  }
  else {
    txt.style.color = 'green';
  }
}

在 HTML 元素中附加 JavaScript 不是一个好的做法,而是可以通过代码检索按钮,然后使用 addEventListener 方法将 change 函数附加到 click 事件,请查看此代码笔以了解其工作原理。

脚本调整

最简单的方法是使用按钮的当前值来确定要执行的操作:

function colorChange(button1) {
    var txt = document.getElementById("txt");
    if (button1.value == "Green") {
        txt.style.color = 'green';
        button1.value == "Red";
    } else {
        txt.style.color = 'red';
        button1.value == "Green";
    }
}

互生

您可以改用全局变量来跟踪按钮的状态,但这是一个不太理想的解决方案:

var txt;
var colorButtonIsGreen = true;
function colorChange() {
    if(!txt) txt = document.getElementById("txt");
    if (colorButtonIsGreen) {
        txt.style.color = 'green';
        button1.value == "Red";
    } else {
        txt.style.color = 'red';
        button1.value == "Green";
    }
    colorButtonIsGreen != colorButtonIsGreen;
}

.HTML:

略微调整的原始 HTML:

<input type="button" value="Green" onclick="colorChange(this);" id="btn">