使用JavaScript访问数据属性

我一直在使用:

var data = element.getAttribute('data-name');

但是使用“数据集”似乎更容易

var data = element.dataset.name

但是我的问题是:无论如何,我可以将var的element.dataset使用吗?例如,我无法使它正常工作:

var dataName = 'test';

var data = element.dataset.dataName;
评论
  • bjstry
    bjstry 回复

    考虑一下您编写的代码实际上是做什么的。

    var data = element.dataset.name is the code which works and you're familiar with – it looks for a property called name inside element.dataset. In this case, name is not an identifier which refers to a variable.

    In exactly the same way, the code element.dataset.dataName looks for a property dataName inside element.dataset. dataName is not seen as an identifier.

    What you want to do is look for a property called test, the content of your variable dataName.

    为此,您需要使用方括号表示法:

    var dataName = 'test';
    
    var data = element.dataset[dataName];
    

    You could also look into variable variables, although many people would recommend against using them in javascript when it is not necessary.

  • Pete
    Pete 回复

    Actually you can do this with bracket-notation.

    var element = document.querySelector('div');
    var dataName = 'test';
    var data = element.dataset[dataName];
    
    console.log(data)
    <div data-test="Test"></div>