[英]Closing 4 functions with different parameters in to array?
我想簡化當前代碼,並通過向它們傳遞等效參數來關閉數組中的所有四個函數。
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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.