我有两个函数,它们的功能基本相同,只是顺序相反。我想了解一些关于如何抽象它们的想法,所以不需要重复太多的代码。我能想到的唯一方法是创建三个额外的函数,然后将被调用。虽然这会使整体尺寸变小一些,但实际上会产生更多的代码行。有没有更好的方法来解决这个问题? 我知道这是一个基本问题,但我找不到任何类似的东西。从两个非常相似的函数中重用代码的最佳方式
function slideRight() {
var source = document.getElementById('pic1').src;
switch (source) {
case imgs[0]:
source=imgs[1];
document.getElementById('bullet1').style.backgroundColor="transparent";
document.getElementById('bullet2').style.backgroundColor="gray";
document.getElementById('bullet3').style.backgroundColor="transparent";
break;
case imgs[1]:
source=imgs[2];
document.getElementById('bullet1').style.backgroundColor="transparent";
document.getElementById('bullet2').style.backgroundColor="transparent";
document.getElementById('bullet3').style.backgroundColor="gray";
break;
case imgs[2]:
source=imgs[0];
document.getElementById('bullet1').style.backgroundColor="gray";
document.getElementById('bullet2').style.backgroundColor="transparent";
document.getElementById('bullet3').style.backgroundColor="transparent";
break;
}
document.getElementById('pic1').src = source;
}
function slideLeft() {
var source = document.getElementById('pic1').src;
switch (source) {
case imgs[0]:
source=imgs[2];
document.getElementById('bullet1').style.backgroundColor="transparent";
document.getElementById('bullet2').style.backgroundColor="transparent";
document.getElementById('bullet3').style.backgroundColor="gray";
break;
case imgs[1]:
source=imgs[0];
document.getElementById('bullet1').style.backgroundColor="gray";
document.getElementById('bullet2').style.backgroundColor="transparent";
document.getElementById('bullet3').style.backgroundColor="transparent";
break;
case imgs[2]:
source=imgs[1]
document.getElementById('bullet1').style.backgroundColor="transparent";
document.getElementById('bullet2').style.backgroundColor="gray";
document.getElementById('bullet3').style.backgroundColor="transparent";
break;
}
document.getElementById('pic1').src = source;
}
编辑:谢谢大家,他们都是好方法!希望我能赶上你的帮助很快!
首先,将这些'switch'语句抽象出来。 – Bergi