简体   繁体   English

如何将多个JS函数组合成一个函数?

[英]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. 我已经google搜索结合我的代码的方法,我尝试了很多解决方案,但他们从来没有帮助过我。

I have 3 divs in html and 3 slightly different JS functions against each div. 我在html中有3个div,对每个div有3个略微不同的JS函数。 Functions are populating js code. 函数填充js代码。

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. 我想组合我的代码而不是有3个函数,如果只有一个函数可以做我想要的同样的事情。

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 ) 使generateStars1,2,3成为常用函数generateStar以接受星数( limit )和要追加的元素( el
  • Removed position object. 删除了position对象。 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() . 同时删除仅在计算中使用的变量xpositionyposition ,并保存Math.random()
  • Removed iterator++ and updated while(iterator <= limits) to while(iterator++ <= limits) 删除了iterator++并更新了while(iterator <= limits) to while(iterator++ <= limits)
  • Removed .appendTo(el) from loop as its a bad practice to manipulate DOM in loop. 从循环中删除.appendTo(el)作为在循环中操作DOM的不良做法。 Instead, created an array and pushed it using $(el).append(divArray) 相反,创建一个数组并使用$(el).append(divArray)推送它

generateStars function generateStars函数

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 只是不要忘记将galaxy类添加到上面的每个div

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. 在这里,您可以传递元素id和系数。

Also, in this case seems that it's better to use ids, because they are unique $('#some-id') . 此外,在这种情况下似乎最好使用id,因为它们是唯一的$('#some-id') On the contrary, same class can be assigned to multiple elements, so jquery will get them all $('.some-class') ; 相反,同一个类可以分配给多个元素,因此jquery将获得所有$('.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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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