【问题标题】:How to extract data attribute that contains a json string using javascript (no JQuery)如何使用javascript(无JQuery)提取包含json字符串的数据属性
【发布时间】:2018-07-23 19:59:30
【问题描述】:

下面的元素有一个包含 json 字符串的数据属性。我无法检索 json 字符串,而是返回 json 字符串的左括号。请看下文。

console.log(document.getElementById('elem').getAttribute('data-hashtags'));
<input id="elem" data-hashtags="["john","barclays-statements","hmrc","laptop","tesco","meat","dinner","drinks","food","cleaning-products","taxi","lunch"]">

【问题讨论】:

  • data-hashtags='["john","barclays-statements","hmrc","laptop","tesco","meat","dinner","drinks","food","cleaning-products","taxi","lunch"]' 试试这个。
  • @ÖzgürCanKaragöz 如果您想将其作为答案,我可以接受。感谢您的帮助

标签: javascript json custom-data-attribute


【解决方案1】:

你把引号弄混了。

应该是这样的:

<input id="elem" data-hashtags="['john','barclays-statements','hmrc','laptop','tesco','meat','dinner','drinks','food','cleaning-products','taxi','lunch']">

不是这样的:

<input id="elem" data-hashtags="["john","barclays-statements","hmrc","laptop","tesco","meat","dinner","drinks","food","cleaning-products","taxi","lunch"]">

正如您在语法高亮中看到的那样,属性标记为橙色(例如data-hashtags),属性值标记为蓝色(例如elem)。您的属性值也标记为橙色,这意味着它们本身被解释为属性。

这是因为在" 之后值“开始”。对于您的第二个",值“结束”,因此该值只是一个括号[。据此,下一个属性将是john,其值为,(此处缺少=,因此无论如何它都是无效的),依此类推。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2017-08-09
    • 2011-05-14
    • 1970-01-01
    相关资源
    最近更新 更多