JS将函数的结果传递给其他函数

时间:2017-09-17 19:25:38

标签: javascript jquery



function oneFunc(elemDiv) {
  $('div.test').each(function() {
    elemDiv = $(this).text();
  });
  return elemDiv;
}

function twoFunc() {
  var fromOneFunc = oneFunc(); // I need to get 1,2,3 to here. But resalt is only last element - (3).
  $('span.get_text').each(function() {
    $(this).text(fromOneFunc); // I am trying for everyone to assign value of ** span ** from ** div **. But its do not work.
  })
}

<div class="test"> 1 </div>
<div class="test"> 2 </div>
<div class="test"> 3 </div>

<span class="get_test"> 1 </span>
<span class="get_test"> 2 </span>
<span class="get_test"> 3 </span>
&#13;
&#13;
&#13;

我需要获取DIV的每个元素的值并传递给 twoFunc 。 但是在结果的twoFunc输出中只有值(3)的元素的最后一个。 我要求帮助理解我的错误。 提前感谢所有并非无动于衷的人。

1 个答案:

答案 0 :(得分:2)

您需要将每个结果添加到数组中:

function oneFunc(){
  var elems = [];
  $('div.test').each(function(){    
     elems.push($(this).text()); 
  });
  return elems;
}

function twoFunc(){
  var fromOneFunc = oneFunc(); // I need to get 1,2,3 to here. But resalt is only last element - (3).
  $('span.get_text').each(function(a, i){
    $(this).text(fromOneFunc[i]); // I am trying for everyone to assign value of ** span ** from ** div **. But its do not work.
  })
}