You need to enable JavaScript to run this app. 如何通过jQuery循环遍历批量将a标签data-endpoint属性嵌入指定div
优惠活动
大模型
产品
解决方案
定价
更多

如何通过jQuery循环遍历批量将a标签data-endpoint属性嵌入指定div

jQuery批量动态属性嵌入实现逻辑

实现思路

直接从下拉菜单的动态渲染<a>标签上读取已挂载的endpoint类数据属性,收集为键值对集合后一次性赋值给目标.form-component div,无需提前写死属性名。

核心实现代码

// 收集目标属性键值对
const endpointAttrPool = {};
// 遍历所有下拉菜单项
$('.dropdown-menu.selectdate > a.dropdown-item').each(function () {
  const $currentItem = $(this);
  // 遍历当前a标签上所有原生dataset属性,动态匹配endpoint类属性
  Object.entries(this.dataset).forEach(([dsKey, dsValue]) => {
    // 筛选出endpoint开头的属性
    if (dsKey.indexOf('endpoint') === 0) {
      // 把dataset驼峰key转回DOM标准的连字符属性名格式
      const realDomAttrName = `data-${dsKey.replace(/[A-Z]/g, '-$1').toLowerCase()}`;
      endpointAttrPool[realDomAttrName] = $currentItem.attr(realDomAttrName);
    }
  });
});
// 批量给目标div嵌入所有收集到的属性
$('.form-component').attr(endpointAttrPool);

适配固定命名规则的简化版本

如果确定所有<a>标签的endpoint属性严格遵循data-endpoint-[data-key值]的命名格式,可以不用遍历全量dataset,直接按规则读取:

const endpointAttrPool = {};
$('.dropdown-menu.selectdate > a.dropdown-item').each(function () {
  const $currentItem = $(this);
  const itemUniqueKey = $currentItem.data('key');
  // 按规则拼接属性名读取值
  const attrName = `data-endpoint-${itemUniqueKey}`;
  endpointAttrPool[attrName] = $currentItem.attr(attrName);
});
$('.form-component').attr(endpointAttrPool);

注意事项

  • 下拉项的选择器可根据实际页面类名调整,确保能精准选中接口渲染生成的所有目标<a>标签,避免误取其他节点的属性
  • 代码会兼容接口动态生成的任意endpoint后缀属性,不需要后续因为接口字段新增重复修改遍历逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 13:36:04