【问题标题】:jQuery: Return multiple dynamic variables from a FOR LOOPjQuery:从 FOR LOOP 返回多个动态变量
【发布时间】:2016-07-08 14:23:41
【问题描述】:

我想计算所有具有.step 类的元素,然后创建一个for 循环并返回选择每个相应元素的变量。这是我的代码:

var steps = $('.step').length;
var i = 0;

for (var i = 0; i < steps; i++) {
    return var step + i = $('.step' + i);
}

编辑:为了让自己清楚,而不是这样做:

var step1 = $('.step1.');
var step2 = $('.step2.');
// etc..  

我想使用for 循环来获取具有.step 类的每个元素并将每个元素返回到不同的变量中,例如:step1step2 等。我该怎么做?

【问题讨论】:

  • return 语句立即退出它出现的函数,返回 一个 值或对象,因此尝试在这样的循环中使用它是没有意义的。跨度>
  • 为什么不只是$('.step')?实际上并不清楚您想要完成什么。
  • 更好的方法是创建一个步长大小的数组,然后将元素保存在数组中
  • 为什么不直接返回 $(".step");
  • 这似乎完全没有意义。生成的数组将与选择 $('.step') 开始相同。如果你想通过索引访问它们,使用eq(),像这样$('.step').eq(0)

标签: javascript jquery variables for-loop


【解决方案1】:

我对你想要的最好的猜测是:

var result = [];
$('.step').each(function(i) {
  result.push( $('.step' + i) );
});
return result;

这将返回一个包含 [所有.step1 元素、所有.step2 元素,...]

【讨论】:

    【解决方案2】:

    如果你想要一个数组中的所有数据,你可以试试这样:

    var data = $(".step").map(function(s, index) {
      return $(".step" + (s + 1));
    });
    console.log(data)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <div class="step step1">1</div>
    <div class="step step2">2</div>
    <div class="step step3">3</div>
    <div class="step step4">4</div>
    <div class="step step5">5</div>
    <div class="step step6">6</div>

    但我宁愿建议您将数据存储在对象中。这会更容易访问。

    var obj = {};
    $(".step").each(function(i, el) {
      var _i = i + 1;
      obj["step" + _i] = $(".step" + _i);
    });
    
    console.log(obj)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <div class="step step1">1</div>
    <div class="step step2">2</div>
    <div class="step step3">3</div>
    <div class="step step4">4</div>
    <div class="step step5">5</div>
    <div class="step step6">6</div>

    【讨论】:

      猜你喜欢
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      相关资源
      最近更新 更多