Javascript 是否关闭阵列中具有不同参数的4个函数?
我可以简化我当前的代码,并通过向数组中传递等效参数来关闭所有四个函数Javascript 是否关闭阵列中具有不同参数的4个函数?,javascript,jquery,arrays,function,dry,Javascript,Jquery,Arrays,Function,Dry,我可以简化我当前的代码,并通过向数组中传递等效参数来关闭所有四个函数 function firstFunction() { if (sound) { var audio = document.getElementById("sound1"); audio.play(); } sound = true; $('#topleft').addClass('litTopLeft'); } function secondFunction() { if (sound
function firstFunction() {
if (sound) {
var audio = document.getElementById("sound1");
audio.play();
}
sound = true;
$('#topleft').addClass('litTopLeft');
}
function secondFunction() {
if (sound) {
var audio = document.getElementById("sound2");
audio.play();
}
sound = true;
$('#topright').addClass('litTopRight');
}
function thirdFunction() {
if (sound) {
var audio = document.getElementById("sound3");
audio.play();
}
sound = true;
$('#bottomleft').addClass('litBottomLeft');
}
function fourthFunction() {
if (sound) {
var audio = document.getElementById("sound4");
audio.play();
};
sound = true;
$('#bottomright').addClass('litBottomRight');
}
所有函数都有类似的参数需要传递,如:
if (sound)
sound = true;
audio.play();
其余参数需要与每个函数等效,如:
var audio = document.getElementById("sound1");
$('#topleft').addClass('litTopLeft');
设置函数参数之间的所有值
function playFunction(soundid, targetid, classname) {
if (sound) {
var audio = document.getElementById(soundid);
audio.play();
}
sound = true;
$('#' + targetid).addClass(classname);
}
然后你就这样称呼它:
playFunction('sound1', 'topleft', 'litTopLeft');
如果目标ID始终与移除了lit前缀的类相同,则可以移除其中一个参数
function playFunction(soundid, classname) {
if (sound) {
var audio = document.getElementById(soundid);
audio.play();
}
sound = true;
var targetid = classname.replace('lit', '').toLowerCase();
$('#' + targetid).addClass(classname);
}
那就是
playFunction('sound1', 'litTopLeft');
不太清楚你在问什么。你知道函数可以有参数,对吧?@RobbyCornelissen我是。这和数组有什么关系?@Barmar我认为函数数组是简化它的最好方法。那会如何简化它?您仍然需要复制每个数组元素中的所有代码。还需要一个参数。CSS类名也不同。或者,类名似乎可以从元素名派生出来。@RobbyCornelissen实际上,由于类名中的camelcase,更容易从另一个方向派生。