如何实现点击按钮依次循环通过Ajax GET加载WordPress文章内容
解决每次点击加载单个URL并循环的问题
直接上修改后的代码:
<button type="button" class="loadAjax">Get Content</button> <div id="target"></div> <script> (function ($) { // 将URL数组和当前索引放在点击事件外部,保持状态 const urls = ['a-nice-post', 'a-small-gallery', 'a-nice-entry']; let currentIndex = 0; $('.loadAjax').click(function(){ // 获取当前要加载的URL const currentUrl = urls[currentIndex]; $.ajax({ url: currentUrl, type:'GET', success: function(data) { $('#target').html($(data).find('.entry-content').html()); // 更新索引,循环回到开头 currentIndex = (currentIndex + 1) % urls.length; }, // 处理请求失败的情况 error: function() { $('#target').html('加载失败,请重试'); // 失败也更新索引,避免卡在此处 currentIndex = (currentIndex + 1) % urls.length; } }); }); })(jQuery); </script>
关键改动说明:
- 状态持久化:把
urls数组和currentIndex索引变量移到点击事件外部,确保每次点击时索引能保留上一次的位置,不会每次都从0开始。 - 移除批量请求:删掉原代码的
for循环,改为每次点击只发送当前索引对应的单个请求,避免一次性加载全部内容。 - 循环索引重置:用
(currentIndex + 1) % urls.length更新索引,当索引到达数组末尾时,取模运算会自动让它回到0,实现循环加载逻辑。 - 错误处理补充:添加
error回调,避免加载失败后索引卡住,同时给用户明确的反馈。
如果要防止用户在请求未完成时重复点击,可以给按钮加禁用逻辑:
$('.loadAjax').click(function(){ const $btn = $(this); // 请求开始时禁用按钮 $btn.prop('disabled', true); const currentUrl = urls[currentIndex]; $.ajax({ url: currentUrl, type:'GET', success: function(data) { $('#target').html($(data).find('.entry-content').html()); currentIndex = (currentIndex + 1) % urls.length; }, error: function() { $('#target').html('加载失败,请重试'); currentIndex = (currentIndex + 1) % urls.length; }, complete: function() { // 请求完成后重新启用按钮 $btn.prop('disabled', false); } }); });
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

