请选择 进入手机版 | 继续访问电脑版

乐心屋资源分享论坛

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 367|回复: 0

使用JavaScript获取data属性值的方法

[复制链接]

264

主题

264

帖子

1万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
10948
发表于 2022-9-10 20:16:05 | 显示全部楼层 |阅读模式
分享:



问题I have next html:
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>Is it possible to get the attributes that beginning with data-, and use it in the JavaScript code like code below? For now I get null as result.
document.getElementById("the-span").addEventListener("click", function(){    var json = JSON.stringify({        id: parseInt(this.typeId),        subject: this.datatype,        points: parseInt(this.points),        user: "H. Pauwelyn"    });});方法:datasetYou need to access the dataset property:
document.getElementById("the-span").addEventListener("click", function() {  var json = JSON.stringify({    id: parseInt(this.dataset.typeid),    subject: this.dataset.type,    points: parseInt(this.dataset.points),    user: "Luïs"  });});Result:
// json would equal:{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑子|栀子舒资源博客|乐心屋资源分享论坛 ( 皖ICP备2021007551号 )

GMT+8, 2023-6-5 19:08 , Processed in 0.050602 second(s), 27 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表