Pobierz atrybuty danych w kodzie JavaScript

Mam następny html:

<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

Czy możliwe jest uzyskanie atrybutów zaczynających się od data- i użycie ich w kodzie JavaScript jak poniżej? Na razie otrzymuję null jako wynik.

document.getElementById("the-span").addEventListener("click", function(){
    var json = JSON.stringify({
        id: parseInt(this.typeId),
        subject: this.datatype,
        points: parseInt(this.points),
        user: "H. Pauwelyn"
    });
});
Author: H. Pauwelyn, 2015-11-17

4 answers

Musisz uzyskać dostęp do dataset własność:

document.getElementById("the-span").addEventListener("click", function() {
  var json = JSON.stringify({
    id: parseInt(this.dataset.typeid),
    subject: this.dataset.type,
    points: parseInt(this.dataset.points),
    user: "Luïs"
  });
});

Wynik:

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }
 63
Author: Josh Crozier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-17 15:21:14

Ponieważ właściwość dataset nie była obsługiwana przez Internet Explorer do wersji 11, możesz użyć getAttribute() zamiast tego:

document.getElementById("the-span").addEventListener("click", function(){
  console.log(this.getAttribute('data-type'));
});

Dokumentacja Zestawu Danych

GetAttribute documentation

 54
Author: MarkPlewis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-17 15:26:15

Możesz uzyskać do niego dostęp jako

element.dataset.points

Itd. Więc w tym przypadku: this.dataset.points

 9
Author: meskobalazs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-17 15:21:38

Spróbuj tego zamiast kodu:

var type=$("#the-span").attr("data-type");
alert(type);
 -10
Author: Akash Agrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-17 16:31:13