You need to enable JavaScript to run this app. for循环绑定点击事件触发XHR始终返回最后一个URL如何解决
优惠活动
大模型
产品
解决方案
定价
更多

for循环绑定点击事件触发XHR始终返回最后一个URL如何解决

问题根源

这是典型的var变量作用域与闭包冲突导致的问题:

  • 你使用var声明的循环变量i属于全局作用域,整个循环过程中所有事件回调共享同一个i变量
  • 循环跑完后i的值已经固定为tratamientos_facial.length(你的场景里最终i值对应peeling疗程的索引),所有按钮点击触发回调时,读取的都是最终状态的i,自然只会拿到固定索引的URL

解决方案

方案1:替换var为let(最简单,推荐)

let拥有块级作用域,每次循环都会生成独立的变量绑定,每个事件回调能拿到对应循环次的i值,只需要改循环声明的一行即可:

let array_asyncs_facial_location = ["Asyncs/facial/radio.html",
                                    'Asyncs/facial/diamante.html',
                                    'Asyncs/facial/limpieza.html',
                                    'Asyncs/facial/peeling.html',
                                    'Asyncs/facial/acne.html',
                                    'Asyncs/facial/rosacea.html',
                                    'Asyncs/facial/pustulas.html'];

let tratamientos_facial = document.getElementsByClassName('tratamientos_facial');

// 把var i改成let i即可
for(let i = 0; i < tratamientos_facial.length; i++){

    tratamientos_facial[i].addEventListener('click', ()=>{

        let xhr = new XMLHttpRequest();

        let url = array_asyncs_facial_location[i];
        xhr.open('GET', url );
        
        xhr.addEventListener('load', ()=>{
            if (xhr.status == 200){
                let plantilla = xhr.response;
                let container_xhr_info = document.querySelector('#container_xhr_info');
                container_xhr_info.innerHTML = plantilla;
            }
        })

        xhr.send();
    })
}

方案2:自定义属性存URL(更稳妥,可维护性更高)

不依赖索引对应关系,后续新增/调整按钮顺序不会出问题:

  1. 给所有tratamientos_facial按钮加data-url属性,值为对应要加载的HTML路径,示例:
<button class="tratamientos_facial" data-url="Asyncs/facial/radio.html">射频疗程</button>
  1. JS直接读取当前点击按钮的属性即可,不需要循环索引匹配:
const container_xhr_info = document.querySelector('#container_xhr_info');
document.querySelectorAll('.tratamientos_facial').forEach(btn => {
  btn.addEventListener('click', () => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', btn.dataset.url);
    xhr.addEventListener('load', () => {
      if(xhr.status === 200) {
        container_xhr_info.innerHTML = xhr.response;
      }
    })
    xhr.send();
  })
})

方案3:IIFE立即执行函数(兼容ES5及更早环境)

如果需要兼容不支持let的老浏览器,用立即执行函数把每次循环的i封入独立作用域:

for(var i = 0; i < tratamientos_facial.length; i++){
  (function(index) {
    tratamientos_facial[index].addEventListener('click', ()=>{
      let xhr = new XMLHttpRequest();
      let url = array_asyncs_facial_location[index];
      xhr.open('GET', url );
      xhr.addEventListener('load', ()=>{
          if (xhr.status == 200){
              let plantilla = xhr.response;
              let container_xhr_info = document.querySelector('#container_xhr_info');
              container_xhr_info.innerHTML = plantilla;
          }
      })
      xhr.send();
    })
  })(i)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 11:06:07