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

jQuery:追加HTML元素时如何添加自定义data属性?

当然可以实现!

完全没问题,jQuery在创建元素的配置对象里提供了两种简洁的方式来添加自定义data-*属性,刚好贴合你想要的写法思路:

方式1:直接指定data-*键名

如果只需要添加单个或少数几个data属性,直接在配置对象里写带连字符的键名(注意要加引号,因为连字符不符合JS标识符规则)就行:

$('#action_existing_email').append($('<option>', { 
  value: templates[i].id, 
  text: templates[i].name,
  'data-version': templates[i].version // 直接生成data-version="对应值"
}));

方式2:用data对象批量设置

如果要添加多个data属性,用data作为键,值是一个包含键值对的对象会更整洁,jQuery会自动把对象里的每个键转换成data-开头的属性:

$('#action_existing_email').append($('<option>', { 
  value: templates[i].id, 
  text: templates[i].name,
  data: {
    version: templates[i].version, // 生成data-version="xxx"
    type: templates[i].type // 生成data-type="xxx"
  }
}));

额外小提示

之后如果要读取这些data属性,用jQuery的.data()方法会更方便,比如$('option').data('version'),它会自动处理属性名的转换,而且jQuery会缓存这些值,性能更好~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:06:13