简体   繁体   中英

How can I combine mutliple JS functions into one function?

I have googled to find out the way to combine my code, I tried many solutions but they never helped me.

I have 3 divs in html and 3 slightly different JS functions against each div. Functions are populating js code.

I want to combine my code like rather than having 3 functions, if there can be only one function that can do the same thing as I want.

What's the best way to do this?

 // Random Stars (function($) { var generateStars = function(){ var $galaxy = $(".galaxy1"); var iterator = 0; while (iterator <= 100){ var xposition = Math.random(); var yposition = Math.random(); var star_type = Math.floor((Math.random() * 100) + 1); var position = { "x" : $galaxy.width() * xposition, "y" : $galaxy.height() * yposition, }; $('<div class="star star-type-' + star_type + '"></div>').appendTo($galaxy).css({ "top" : position.y, "left" : position.x }); iterator++; } }; generateStars(); var generateStars2 = function(){ var $galaxy = $(".galaxy2"); var iterator = 0; while (iterator <= 25){ var xposition = Math.random(); var yposition = Math.random(); var star_type = Math.floor((Math.random() * 25) + 1); var position = { "x" : $galaxy.width() * xposition, "y" : $galaxy.height() * yposition, }; $('<div class="star star-type-' + star_type + '"></div>').appendTo($galaxy).css({ "top" : position.y, "left" : position.x }); iterator++; } }; generateStars2(); var generateStars3 = function(){ var $galaxy = $(".galaxy3"); var iterator = 0; while (iterator <= 50){ var xposition = Math.random(); var yposition = Math.random(); var star_type = Math.floor((Math.random() * 50) + 1); var position = { "x" : $galaxy.width() * xposition, "y" : $galaxy.height() * yposition, }; $('<div class="star star-type-' + star_type + '"></div>').appendTo($galaxy).css({ "top" : position.y, "left" : position.x }); iterator++; } }; generateStars3(); })(jQuery); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div class="galaxy1"></div> <div class="galaxy2"></div> <div class="galaxy3"></div> </body> 

Configuration is a key pattern in a slightly varied parameters, but similar (or in your case, exact) logic:

code

var generateStars = function($galaxy, threshold){

  var iterator = 0;

  while (iterator <= threshold){
      var xposition = Math.random();
      var yposition = Math.random();
      // using the 'threshold' parameter passed into the function
      var star_type = Math.floor((Math.random() * threshold) + 1);
      // no need to re-initialized '$galaxy' as it's now passed into the function
      var position = {
          "x" : $galaxy.width() * xposition,
          "y" : $galaxy.height() * yposition,
      };

      $('<div class="star star-type-' + star_type + '"></div>').appendTo($galaxy).css({
          "top" : position.y,
          "left" : position.x
      });

      iterator++;
  }

};

usage

// getting all the html elements
var $galaxy1 = $(".galaxy1");
var $galaxy2 = $(".galaxy2");
var $galaxy3 = $(".galaxy3");

// passing the properties of the found elements and the threshold 
// to be utilized inside the function
generateStars($galaxy1, 100);
generateStars($galaxy2, 25);
generateStars($galaxy3, 50);

You can try something like this:

Changes:

  • Made generateStars1,2,3 to a common function generateStar to accept number of stars( limit ) and element to append( el )
  • Removed position object. Since this object was only used once, moved logic there and removed object.
  • Also remove variables xposition and yposition as only used in calculations and holds Math.random() .
  • Removed iterator++ and updated while(iterator <= limits) to while(iterator++ <= limits)
  • Removed .appendTo(el) from loop as its a bad practice to manipulate DOM in loop. Instead, created an array and pushed it using $(el).append(divArray)

generateStars function

function generator(el, limit) {
  var iterator = 0;
  var divs = [];
  while (iterator++ <= limit) {
    var star_type = Math.floor((Math.random() * limit) + 1);
    var $div = $('<div class="star star-type-' + star_type + '"></div>').css({
      "top": ($(el).height() * Math.random()),
      "left": ($(el).width() * Math.random())
    })
    divs.push($div)
  }
  $(el).append(divs)
};

Working Demo

 function generator(el, limit) { var iterator = 0; var divs = []; while (iterator++ <= limit) { var star_type = Math.floor((Math.random() * limit) + 1); var $div = $('<div class="star star-type-' + star_type + '"></div>').css({ "top": ($(el).height() * Math.random()), "left": ($(el).width() * Math.random()) }) divs.push($div) } $(el).append(divs) }; (function($) { var generateStars = function() { var limits = [100, 25, 50]; $('div[class^="galaxy"]').each(function(i, el) { generator(el, limits[i]) }) } generateStars(); })(jQuery); 
 .star { border: 1px solid gray; width: 10px; height: 10px; display: inline-block; margin: 0 2px; } [class^='galaxy'] { padding: 5px; border: 1px solid gray; margin: 5px 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <body> <div class="galaxy1"></div> <div class="galaxy2"></div> <div class="galaxy3"></div> </body> 

Try something like that:

 var star_type_multipler = { 0: 100, 1: 25, 2: 50 } var $i = 0; $('.galaxy').each(function() { var $galaxy = $(this); var iterator = 0; var multipler = star_type_multipler[$i++] while (iterator <= multipler){ var xposition = Math.random(); var yposition = Math.random(); var star_type = Math.floor((Math.random() * multipler) + 1); var position = { "x" : $galaxy.width() * xposition, "y" : $galaxy.height() * yposition, }; $('<div class="star star-type-' + star_type + '">x</div>').appendTo($galaxy).css({ "top" : position.y, "left" : position.x }); iterator++; } }); 
 .star { position: fixed; } body { width: 500px; height: 500px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div class="galaxy1 galaxy">&nbsp;</div> <div class="galaxy2 galaxy">&nbsp;</div> <div class="galaxy3 galaxy">&nbsp;</div> </body> 

Just don't forget to add galaxy class to each div like above

var options = [100, 25, 50];

$("div[class^='galaxy']").each(function(index){
    generateStars($(this), options[index]);
});

function generateStars($galaxy, limit){
  for(var iterator = 0; iterator < limit, iterator++){
     var star_type = Math.floor((Math.random() * limit) + 1);
     $('<div class="star star-type-' + star_type + '"></div>').appendTo($galaxy).css({
        "top" : $galaxy.height() * Math.random(),
        "left" : $galaxy.width() * Math.random()
     });
  }
};

Just pass the arguments that are variable, ie can change from case to case. Here, you can pass the element id and a coefficient.

Also, in this case seems that it's better to use ids, because they are unique $('#some-id') . On the contrary, same class can be assigned to multiple elements, so jquery will get them all $('.some-class') ;

var generateStars = function(elementId, coef){

  var $galaxy = $(elementId);
  var iterator = 0;

  while (iterator <= coef){
      var xposition = Math.random();
      var yposition = Math.random();
      var star_type = Math.floor((Math.random() * coef) + 1);
      var position = {
          "x" : $galaxy.width() * xposition,
          "y" : $galaxy.height() * yposition,
      };

      $('<div class="star star-type-' + star_type + '"></div>').appendTo($galaxy).css({
          "top" : position.y,
          "left" : position.x
      });

      iterator++;
  }

};

generateStars('#galaxy1', 100);
generateStars('#galaxy2', 50);
generateStars('#galaxy3', 25);

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