简体   繁体   中英

Closing 4 functions with different parameters in to array?

I could like to simplify my current code and close all four functions in array with passing equivalent parameters in to them .

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');

}

All functions have similar parameters that need to be passed by like :

 if (sound)
 sound = true;
 audio.play();

Rest of the parameters need to be equivalent to each function like:

var audio = document.getElementById("sound1");
$('#topleft').addClass('litTopLeft');

Make all the values that vary between the functions parameters.

function playFunction(soundid, targetid, classname) {
  if (sound) {
    var audio = document.getElementById(soundid); 
    audio.play(); 
  }
  sound = true;
  $('#' + targetid).addClass(classname);
}

Then you call it like:

playFunction('sound1', 'topleft', 'litTopLeft');

You can remove one of the parameters if the target ID is always the same as the class with lit prefix removed.

function playFunction(soundid, classname) {
  if (sound) {
    var audio = document.getElementById(soundid); 
    audio.play(); 
  }
  sound = true;
  var targetid = classname.replace('lit', '').toLowerCase();
  $('#' + targetid).addClass(classname);
}

Then it's just

playFunction('sound1', 'litTopLeft');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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