一次一个地通过一系列函数传递ID



我有多个图像。

<img src="fruits/lychee.png" class ="fruit" id="fruitl156">
<img src="fruits/cranberry.png" class ="fruit" id="fruitl141">
<img src="fruits/avocado.png" class ="fruit" id="fruitl214">

当页面加载时,将显示随机数量的图像。我想通过一系列函数传递每个可见的图像ID,每次一个。

var ID = '';
$('#getIDs').click(function(){
   ID = $('.fruit:visible').map(function () {
      return this.id;
   }).get();
});

这是我想一次传递给每个ID的一系列函数。

function showInfo( anID, var2, var3 ){
    //do something 
    getThumbs( anID, newvar1);
});
function getThumbs( anID, newvar1){
    //do something
    showRates( anID, anothervar1, anotherVar2); 
});
function showRates( anID, anothervar1, anotherVar2){
    //do something 
});

所以当第一个ID通过所有函数发送时,第二个ID通过函数发送,以此类推…我该怎么做呢?

编辑:

它是一个函数链。每个函数触发下一个函数

这个怎么样?

$('#getIDs').click(function(){
   $('.fruit:visible').each(function () {
      thisId = this.id;
      showInfo( thisId, var2, var3 );
      getThumbs( thisId, newvar1);
      showRates( thisId, anothervar1, anotherVar2);
   });
});

我相信这就是你想要的。

获取所有可见图像的ids,然后使用它来调用相应的函数并不是一个好主意。

我做了什么:

  • 通过class选择器(水果)获取所有元素并循环遍历所有图像。
  • 检查当前图像是否在循环中可见并为每个图像实例调用相应的函数。

JS代码:

function showInfo( anID, var2, var3 ){
   var newvar1;
   //do something with var`s & assign result to newvar1
  return newvar1;
});
function getThumbs( anID, newvar1){
   var arr[]; 
   //do something with newvar1 and generate anothervar1, anotherVar2
   arr[0] = anothervar1;
   arr[1] = anothervar2;
   return arr;
});
// array arr contains 2 variable definitions 'anothervar1, anotherVar2'
function showRates( anID, arr){
   //final process array arr do required operation
});
$('.fruit').each(function(){
   var $curElement = $(this);
   var $id = $curElement.attr('id');
   var ret;
   if ($curElement.is(":visible")){
     //get the parameters required for the below function and pass it.
     ret = howInfo( $id, var2, var3 );
     ret = getThumbs( $id, ret);
     showRates( $id, ret);
  }
});

最新更新