【问题标题】:Reading a html attribute as an array using Javascript / Jquery使用 Javascript / Jquery 将 html 属性作为数组读取
【发布时间】:2022-01-07 05:05:03
【问题描述】:

感觉这应该很简单

我有一些这样的 html(我无法控制 html)

<div class="something" data-spec="['thing','another-thing','one-more-thing']">Stuff</div>

我正在尝试将数据规范作为数组读取,而不必将其分解为字符串,将其拆分然后将值推送到数组中。

如果我这样做:

let elem = $('.something')
let attr = elem[0].attributes['data-spec']
console.log(attr)

返回:

data-spec="['thing','another-thing','one-more-thing']"

有没有办法将 data-spec 读取为数组对象?

谢谢。

【问题讨论】:

  • 更改您的输出以使其成为有效的 JSON? (将 ' 更改为 ")然后 JSON.parse。从源头修复它,而不是在运行时破解它。

标签: javascript jquery arrays object


【解决方案1】:

尝试用双引号替换所有单引号,然后使用JSON.parse

const dataSpec="['thing','another-thing','one-more-thing']"

JSON.parse(dataSpec.replace(/'/g, '"'))

const dataSpec = "['thing','another-thing','one-more-thing']"
const array = JSON.parse(dataSpec.replace(/'/g, '"'))
console.log(array);

【讨论】:

  • 不错的一个。感谢您的帮助。
【解决方案2】:

否则我会说JSON.parse(),但由于这些是单引号,你不能直接这样做。

可怕的选项是eval(),但我认为一个快乐的中间立场(如果字符串中有其他引号可能会中断)是

const attrString = elem[0].attributes['data-spec'];
// replace single quotes with double quotes for JSON parsing
const attr = JSON.parse(attrString.replace(/'/g, '"')); 

【讨论】:

    【解决方案3】:

    不确定您是否可以直接做您想做的事,但作为一种解决方法,您可以使用正则表达式提取引号之间的所有内容,例如:

    var test = "data-spec=\"['thing','another-thing','one-more-thing']\"";
    var result = test.match(/(?<=\').*(?=\')/);
    
    console.log(result);
    //will log : Array [ "thing','another-thing','one-more-thing" ]
    

    注意:也许您必须使用 JSON.stringify(elem[0].attributes['data-spec']) 才能拥有与示例中相同的字符串“test”

    【讨论】:

      【解决方案4】:

      使用带有querySelectorVanilla 方法来获取第一个具有class something 的匹配元素。

      const something = document.querySelector(".something");
      const attr = something.dataset.spec; // You could also use something.getAttribute("data-spec")
      console.log(attr); // "['thing','another-thing','one-more-thing']"
      

      使用带有 flag g 的 match 获取引号 "'" 之间的值,以匹配引号之间的所有可能值。

      const elementsQuoted = attr.match(/'(.*?)'/g);//["'thing'", "'another-thing'", "'one-more-thing'"]
      //Remove quotations by replacing any quote with empty string.
      const array = elementsQuoted.map(element=>element.replaceAll("'",''));
      

      结果

      console.log(attr);//['thing', 'another-thing', 'one-more-thing']
      

      注意:您可以按正则表达式模式 /','/ 进行拆分以获取数组的值。但它只需要替换第一个元素中的左括号和最后一个元素的右括号。

      attr.split(/','/g);//["['thing", 'another-thing', "one-more-thing']"]
      

      Never use eval!

      作为@AKX 的答案,JSON 方法 parse 通过用双引号替换单引号来获利,因为 JSON 标准需要双引号并且不接受单引号。

      【讨论】:

        猜你喜欢
        • 2013-12-23
        • 1970-01-01
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 2016-07-31
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        相关资源
        最近更新 更多