You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在JavaScript中获取HTML data属性?含点击按钮展示值场景

在JavaScript中获取HTML data属性的方法

先理清核心思路:获取data属性的两种常用方式

HTML5的data-*自定义属性,在JavaScript里有两种非常实用的获取方式,我给你拆解清楚:


1. 通用获取data属性的方法

  • 方式一:用getAttribute()直接获取
    这是最基础的兼容写法,不管是data-前缀的属性还是普通HTML属性都能搞定,直接写完整的属性名就行:
// 先拿到目标元素
const targetElement = document.querySelector('.blue-button');
// 获取指定data属性
const nameValue = targetElement.getAttribute('data-name');
const descValue = targetElement.getAttribute('data-description');
  • 方式二:用dataset对象简化操作
    HTML5专门提供了dataset对象,它会自动忽略data-前缀,还会把属性名里的连字符转成驼峰命名(比如data-description对应dataset.description),用起来更清爽:
const targetElement = document.querySelector('.blue-button');
// 直接通过dataset访问,不用写data-前缀
const nameValue = targetElement.dataset.name;
const descValue = targetElement.dataset.description;

2. 实现「点击按钮展示属性值」的完整代码

注意:你提供的代码里把按钮写成了<script>标签,这没法实现点击交互哦,我帮你修正成<button>元素,这才是符合需求的结构:

修正后的HTML结构

<form action="http://serverhost/postdata" method="POST">
  <button class="blue-button" data-name="aaa" data-description="bbb">点击查看属性值</button>
</form>

对应的JavaScript代码(可放入myscript.js

// 给按钮绑定点击事件
document.querySelector('.blue-button').addEventListener('click', function(e) {
  // 阻止表单默认提交行为,避免页面跳转
  e.preventDefault();
  
  // 用dataset快速获取属性值
  const name = this.dataset.name;
  const description = this.dataset.description;
  
  // 这里用alert展示结果,你也可以改成把内容插入到页面的某个元素里
  alert(`data-name的值:${name}\ndata-description的值:${description}`);
});

如果你确实需要从<script>标签获取data属性(不太推荐这么用)

如果你的场景必须读取script标签的data属性,可以这么写:

// 获取带class的script元素
const scriptElement = document.querySelector('script.blue-button');
// 给页面里的按钮绑定事件(假设页面有个id为showBtn的按钮)
document.getElementById('showBtn').addEventListener('click', function() {
  const name = scriptElement.dataset.name;
  const description = scriptElement.dataset.description;
  alert(`data-name: ${name}\ndata-description: ${description}`);
});

小提醒:dataset是HTML5的特性,现代浏览器都支持,比getAttribute()更简洁;如果要兼容非常老旧的浏览器,getAttribute()会更稳妥~

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

火山引擎 最新活动