如何使用jQuery循环变量名

时间:2016-05-02 13:33:17

标签: javascript jquery loops

如何通过以下方式循环jQuery:

<select class="js-setup">
    <option value="">Choose</option>
    <option value="setup1" data-setup0="1" data-setup1="4" data-setup2="3" data-setup3="3">1 Ananas, 4 Eggs, 3 Apples, 3 Banana</option>
    <option value="setup2" data-setup0="1" data-setup1="4" data-setup2="4" data-setup3="2">1 Ananas, 4 Eggs, 4 Apples, 2 Banana</option>
    <option value="setup3" data-setup0="1" data-setup1="4" data-setup2="5" data-setup3="1">1 Ananas, 4 Eggs, 5 Apples, 1 Banana</option>
</select>

...所以我不必重复这些线路?

// var setupCount == 4
$setup.on('change',function(){
   var $that = $(this),
       setup0,
       setup1,
       setup2,
       setup3;

   // get user-selected setup
   setup0 = $that.find(':selected').data('setup0');
   setup1 = $that.find(':selected').data('setup1');
   setup2 = $that.find(':selected').data('setup2');
   setup3 = $that.find(':selected').data('setup3');

  // set user-selected to the progress-indicator
   $('.js-availableToSelect:eq(0)').text(setup0);
   $('.js-availableToSelect:eq(1)').text(setup1);
   $('.js-availableToSelect:eq(2)').text(setup2);
   $('.js-availableToSelect:eq(3)').text(setup3);
});

该应用程序知道(来自var«setupCount»)总共有4种数据设置可能性。

2 个答案:

答案 0 :(得分:1)

您可以使用for循环来迭代,eq()可以按索引选择元素。

// var setupCount == 4
$setup.on('change', function () {
    var selected = $(this).find(':selected'); // Cache for better performance

    for(var i = 0; i < 3; i++) {
        $('.js-availableToSelect').eq(i) // Get the element at `i`th index
            .text(selected.data('setup' + i)); // Set the value of data attribute
    }
});

您还可以使用text()进行回调。

$setup.on('change', function () {
    var selected = $(this).find(':selected'); // Cache for better performance

    $('.js-availableToSelect').text(function(i) {
        return selected.data('setup' + i);
    });
});

答案 1 :(得分:1)

这很简单:

&#13;
&#13;
var setup = [];
for(i = 0; i < 4; i++) {
  setup[i] = $that.find(":selected").data('setup'+i);
  $('.js-availableToSelect:eq('+i+')').text(setup[i]);
}  
&#13;
&#13;
&#13;