javascript - Getting the value of the first object in dataset on a HTML DOM with javascript
问题描述
So I have a DOM like this:
<div data-info="{"partnerLink":"https://bing.com","fillColor":"rgba(10,91,144,1)"}"></div>
Is there any way to get the value of partnerLink (in this case https://bing.com) in JS?
I know it would be better to have data-partnerLink and data-fillColor but this is what I have for now.
解决方案
Fix the object. The quotes you are using are wrong. Access the element using querySelector and get the attributes using getAttribute. Using dot notation print the object property
var a=document.querySelector('div')
var b=a.getAttribute('data-info');
console.log(JSON.parse(b).partnerLink)
<div data-info='{"partnerLink":"https://bing.com","fillColor":"rgba(10,91,144,1)"}'></div>
推荐阅读
- django - Django项目中docker-compose中的Postgres连接问题
- amazon-web-services - 调用 SSH 时 Shell 脚本停止
- elasticsearch - Elasticsearch 对过滤条件组进行“或”搜索
- c++ - 部分模板特化:std::allocator_traits?
- homebrew - 尝试在 MacOS 上更新 Homebrew 但收到错误消息“LibreSSL 错误”
- json - 阅读 REST API JSON 回复
- leaflet - 如何以编程方式获取 PixiOverlay 标记并通过绘制的边界获取它们的属性
- c# - 如何将“System.Windows.Controls.TextBlock”转换为“System.Windows.Controls.Control”WPF C#
- windows - UWP 画布像素操作
- r - 带变量 R 的 sum 函数