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

通过querySelectorAll循环动态获取父元素title并赋值子元素

解决方案

问题出在你循环里的document.querySelector(".mat_option").title——这个方法只会返回页面中第一个匹配.mat_option选择器的元素的title,所以所有新创建的子div都会显示同一个静态值。

你只需要直接使用循环中当前遍历到的item元素来获取对应的title即可,修正后的代码如下:

function onloaddiv() {
  for (const item of document.querySelectorAll('.mat_option')) {
    const divp = document.createElement("div"); // 加上const避免全局变量污染
    const var2 = item.title; // 直接取当前遍历元素的title
    divp.innerHTML = var2;
    item.append(divp);
  }
}

关键说明:

  • querySelectorAll('.mat_option')返回所有匹配元素的集合,循环中的item对应每一个单独的.mat_option元素
  • 直接通过item.title获取当前元素的动态title,确保每个子div对应父元素的专属值
  • 给divp和var2添加const声明,避免不必要的全局变量污染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:40:31