Javascript 事件 - 如何使此代码变干

Javascript events - how to make this code DRY

我正在学习 JavaScript。有人可以帮我把这段代码变干吗(不要重复自己)?该代码是关于通过单击特定的 connected-with 按钮来更改段落的颜色。我不知道如何使 changeColor 函数适用于特定代码块而不制作此函数的新版本。

var greenPar = document.getElementById("green-paragraph");
var greenColorBtn = document.getElementById("greenColorBtn");
var redPar = document.getElementById("red-paragraph");
var redColorBtn = document.getElementById("redColorBtn");
greenColorBtn.addEventListener("click", changeColorGreen);
redColorBtn.addEventListener("click", changeColorRed);

function changeColorGreen() {
    if (greenPar.className == "") {
        greenPar.className = "green"; //.green{ color:green;}
    } else {
        greenPar.className = "";
    }
}

function changeColorRed() {
    if (redPar.className == "") {
        redPar.className = "red"; //.red{ color:red;}
    } else {
        redPar.className = "";
    }
}

使用常用函数作为点击处理程序并将颜色值作为参数传递。

因为您将在处理程序中使用 this 值,请使用 Function#bind 并传递 this-context, 第二个参数将是要比较的颜色值。

var greenPar = document.getElementById("green-paragraph");
var greenColorBtn = document.getElementById("greenColorBtn");

var redPar = document.getElementById("red-paragraph");
var redColorBtn = document.getElementById("redColorBtn");

greenColorBtn.addEventListener("click", changeColor.bind(greenColorBtn, 'green'));
redColorBtn.addEventListener("click", changeColor.bind(redColorBtn, 'red'));

function changeColor(color) {
  var thisElem = this;
  if (thisElem.className == "") {
    thisElem.className = color;
  } else {
    thisElem.className = "";
  }
}

您可以将 changeColor 函数包装在匿名函数中,以便您可以传递参数:

var greenPar = document.getElementById("green-paragraph");
var greenColorBtn = document.getElementById("greenColorBtn");

var redPar = document.getElementById("red-paragraph");
var redColorBtn = document.getElementById("redColorBtn");

greenColorBtn.addEventListener("click", function () { changeColor(greenPar, "green"); });
redColorBtn.addEventListener("click", function () { changeColor(redPar, "red"); });

function changeColor(element, value){
    if(element.className == ""){
        elmement.className = value;
    }else{
        element.className = "";
    }  
}

你可以这样试试

   function getElementByid (_id) {
     var element = document.getElementById(_id);
     return element;
    }

    function changeColor (_id,_colorClass) {
        var element=getElementByid (_id);
        if (element.className==""){
            element.className=_colorClass;
        }else {
            element.className="";
        }
    }
    getElementByid ("greenColorBtn").addEventListener("click",
        changeColor ("green-paragraph","green"));

    getElementByid ("redColorBtn").addEventListener("click",
        changeColor ("red-paragraph","red")); `