You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于随机循环ID序列实现按钮点击按序加载数据的技术咨询

需求与现有代码

我需要实现点击nextButton按钮时,按照预先生成的随机ID序列顺序展示对应数据。

现有按钮HTML代码

<button id="nextButton" data-id="{{$data_number->id}}" data-no="{{ $key_number }}" type="button" class="btn btn-primary pull-right btn-md" style="margin-left:20px !important;"> 
  Selanjutnya
  <i class="fa fa-chevron-circle-right"></i>
</button>

随机ID序列相关

该序列通过Laravel循环生成:

@foreach($soals as $data_number)
  {{$data_number->id}}
@endforeach

生成的具体ID序列:

29 14 12 43 16 33 44 19 5 3 34 30 25 37 31 18 36 11 41 17 38 1 48 28 50 40 15 22 47 45 42 6 8 10 4 26 23 2 9 35 32 13 21 39 49 20 24 46 7 27

现有jQuery代码

$('#nextButton').click(function() {
  var $this = $(this);
  $('#wrap-soal').html('<center><i class="fa fa-spinner fa-spin" style="font-size: 30 pt; color: #12b9cc; margin: 15px;" aria-hidden= "true"></i></center>');
    $('#no_soal_detail').html($this.attr('data-no'));
    var id_soal = $this.attr('data-id'); $.ajax({
      type: "GET",
      url: "{{ url('siswa/ujian/get-soal') }}/" + id_soal,
      success: function(data) {
        $('#wrap-soal').html(data);
      }
    })
  });
});
解决方案

核心思路是存储完整的随机ID序列,维护当前位置索引,每次点击按钮时取下一个ID发起请求:

1. 存储随机ID序列到JS变量

在页面中通过Laravel输出转换为JavaScript数组:

<script>
// 将Laravel生成的随机ID序列转为JS数组
const randomIds = [@foreach($soals as $data_number){{$data_number->id}}@if(!$loop->last),@endif @endforeach];
// 当前索引,初始值根据页面已加载的第一个ID调整,默认从0开始
let currentIndex = 0;
</script>

2. 修改按钮点击事件逻辑

更新jQuery代码,实现按序列顺序切换:

$('#nextButton').click(function() {
  const $this = $(this);
  
  // 计算下一个索引,到达序列末尾可选择循环或禁用按钮
  currentIndex = (currentIndex + 1) % randomIds.length;
  
  // 获取下一个ID并更新按钮的data属性
  const nextId = randomIds[currentIndex];
  $this.attr('data-id', nextId);
  $this.attr('data-no', currentIndex + 1); // 题号从1开始计数
  
  // 显示加载状态
  $('#wrap-soal').html('<center><i class="fa fa-spinner fa-spin" style="font-size: 30pt; color: #12b9cc; margin: 15px;" aria-hidden="true"></i></center>');
  $('#no_soal_detail').html(currentIndex + 1);
  
  // 发起AJAX请求获取对应数据
  $.ajax({
    type: "GET",
    url: "{{ url('siswa/ujian/get-soal') }}/" + nextId,
    success: function(data) {
      $('#wrap-soal').html(data);
    },
    error: function() {
      $('#wrap-soal').html('<p>加载题目失败,请重试</p>');
    }
  });

  // 可选:序列遍历完后禁用按钮
  if (currentIndex === randomIds.length - 1) {
    $this.prop('disabled', true).addClass('btn-disabled');
  }
});

内容的提问来源于stack exchange,提问作者dwi prihta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:54:21