在javascript中组合两个函数
我有这两个函数,它们的代码基本相似。。所以我想把它们合并成一个函数在javascript中组合两个函数,javascript,Javascript,我有这两个函数,它们的代码基本相似。。所以我想把它们合并成一个函数 previousMonthImg.onclick=function(){ 如果(!(monthSelect.value==“一月”和&yearSelect.value==“2010”)){ monthSelect.selectedIndex--; 如果(monthSelect.selectedIndex==-1){ monthSelect.value=“十二月”; yearSelect.selectedIndex--; } }
previousMonthImg.onclick=function(){
如果(!(monthSelect.value==“一月”和&yearSelect.value==“2010”)){
monthSelect.selectedIndex--;
如果(monthSelect.selectedIndex==-1){
monthSelect.value=“十二月”;
yearSelect.selectedIndex--;
}
}
triggerEvent(每月选择“变更”);
triggerEvent(年份选择“变更”);
};
nextMonthImg.onclick=function(){
如果(!(monthSelect.value==“12月”和&yearSelect.value==“2030”)){
选择月份。选择指数++;
如果(monthSelect.selectedIndex==-1){
monthSelect.value=“一月”;
yearSelect.selectedIndex++;
}
}
triggerEvent(每月选择“变更”);
triggerEvent(年份选择“变更”);
}
您可以按如下方式组合这两种功能:
monthImg.onclick = function() {
let maxMonth = 0;
let minMonth = 0;
if (!(monthSelect.value === "Dec" && yearSelect.value === "2030")) {
maxMonth = 1;
}
if (!(monthSelect.value === "Jan" && yearSelect.value === "2010")) {
minMonth = 1;
}
if ((maxMonth) || (minMonth)) {
if (maxMonth) {
monthSelect.selectedIndex++;
} else {
monthSelect.selectedIndex--;
}
if (monthSelect.selectedIndex === -1) {
if (minMonth) {
monthSelect.value = "Jan";
yearSelect.selectedIndex++;
} else {
monthSelect.value = "Dec";
yearSelect.selectedIndex--;
}
}
}
triggerEvent(monthSelect, "change");
triggerEvent(yearSelect, "change");
}
但这会增加函数的复杂性。您仍然可以将它们分开。您可以使用函数来创建事件处理程序
function makeHandler(monthEnd, monthStart, year, inc) {
return function(){
if (!(monthSelect.value === monthEnd && yearSelect.value === year)) {
monthSelect.selectedIndex += inc;
if (monthSelect.selectedIndex === -1) {
monthSelect.value = monthStart;
yearSelect.selectedIndex += inc;
}
}
triggerEvent(monthSelect, "change");
triggerEvent(yearSelect, "change");
}
};
previousMonthImg.onclick = makeHandler("Jan", "Dec", "2010", -1);
nextMonthImg.onclick = makeHandler("Dec", "Jan", "2030", 1);
您可以使用这个:
const myNewFunc = (month, year, num) => {
if (!(monthSelect.value === month && yearSelect.value === year)) {
monthSelect.selectedIndex = monthSelect.selectedIndex + num;
if (monthSelect.selectedIndex === -1) {
monthSelect.value = month == 'Jan' ? 'Dec' : 'Jan';
yearSelect.selectedIndex = yearSelect.selectedIndex + num * -1;
}
}
triggerEvent(monthSelect, 'change');
triggerEvent(yearSelect, 'change');
}
nextMonthImg.addEventListener('click', () => {myNewFunc(...)})
previousMonthImg.addEventListener('click', () => {myNewFunc(...)})
我会把它们分开。它们执行两种非常不同的er功能。