简体   繁体   English

如何组合两块相似的 JavaScript 代码?

[英]How do I combine two blocks of similar JavaScript Code?

I'm trying to find a way of writing some sort of function so that I don't have to keep rewriting the same type of code.我正在尝试找到一种编写某种 function 的方法,这样我就不必继续重写相同类型的代码。

As you can see below, both blocks of code are pretty much the same except one is for the lunchTimeSelector and the other is for the napTimeSelector ?正如您在下面看到的,两个代码块几乎相同,除了一个用于lunchTimeSelector另一个用于napTimeSelector Is there any way to write a function so that I can just automate this by just inputting an array like [lunchTimeSelector, napTimeSelector, dinnerTimeSelector] , etc. into a function to replace this code?有什么方法可以编写 function 以便我可以通过将[lunchTimeSelector, napTimeSelector, dinnerTimeSelector]等数组输入 function 来替换此代码来自动执行此操作?

// Activates Lunch selector
var lunchTimeSelector =  document.getElementById("lunchTimeSelector");

var lunchEvent = function()
{
    lunchtime = lunchTimeSelector.value;
};

lunchTimeSelector.addEventListener("change", lunchEvent);





// Activates Nap-Time selector
var napTimeSelector =  document.getElementById("napTimeSelector");

var napEvent = function()
{
    naptime = napTimeSelector.value;
};

napTimeSelector.addEventListener("change", napEvent);

You could implement it like so:你可以像这样实现它:

function addChangeEvent(id, handler){
    document.getElementById(id).addEventListener("change", handler);
}
[["lunchTimeSelector", function(){lunchtime = this.value}], 
 ["napTimeSelector", function(){naptime = this.value}]]
    .forEach(([id,handler])=>addChangeEvent(id,handler));

maybe you can try:也许你可以试试:

// wrap all your logic 
function lanuchNapTimeSelector(id,state){

 var target =  document.getElementById(id);

// your handelers
 var lunchEvent = function()
 {
    lunchtime = target.value;
 };

 var napEvent = function()
 {
    naptime = target.value;
 };

 target.addEventListener("change", state === "nap" ? napEvent : 
 lunchEvent);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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