简体   繁体   English

使用JavaScript获取HTML DOM上数据集中第一个对象的值

[英]Getting the value of the first object in dataset on a HTML DOM with javascript

So I have a DOM like this: 所以我有一个这样的DOM:

<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? 有什么方法可以在JS中获得partnerLink的值(在本例中为https://bing.com )?

I know it would be better to have data-partnerLink and data-fillColor but this is what I have for now. 我知道最好有data-partnerLink和data-fillColor,但这是我现在所拥有的。

Fix the object. 修复对象。 The quotes you are using are wrong. 您使用的引号是错误的。 Access the element using querySelector and get the attributes using getAttribute. 使用querySelector访问元素,并使用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> 

First, you need to fix your quotes like so: 首先,您需要像这样修改报价:

<div data-info='{"partnerLink":"https://bing.com","fillColor":"rgba(10,91,144,1)"}'></div>

(All I changed were the very first and last "" into '' so it wouldn't interfere with the inner quotes). (我所做的只是将第一个和最后一个""改成''因此不会干扰内部引号)。

And you can do it like this: 您可以这样做:

 var div = document.querySelector("div"); //Add an ID and use getElementById if there's more than one div var partnerLink = JSON.parse(div.getAttribute("data-info")).partnerLink; console.log(partnerLink); 
 <div data-info='{"partnerLink":"https://bing.com","fillColor":"rgba(10,91,144,1)"}'></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM