html - Cum pot obține valorile atributelor data în codul JavaScript?


Am următorul html:

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

Este posibil să obții atributele care încep cu data- și să le folosești în codul JavaScript ca în codul de mai jos? Deocamdată obțin null ca rezultat.

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"
    });
});

Răspuns #1

Trebuie să accesezi proprietatea dataset:

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"
  });
});

Rezultat :

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }

Răspunsul #2

Deoarece proprietatea dataset nu a fost suportată de Internet Explorer până la versiunea 11, s-ar putea să doriți să folosiți în schimb getAttribute():

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

Documentația setului de date

documentația getAttribute

Răspunsul #3

De asemenea, poți prelua atributele cu metoda getAttribute(), care va returna valoarea unui atribut HTML specific.

const elem = document.getElementById('the-span');

const typeId = elem.getAttribute('data-typeId');
const type   = elem.getAttribute('data-type');
const points = elem.getAttribute('data-points');
const important = elem.getAttribute('data-important');

console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`
);
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

Răspunsul #4

Poți să accesezi aceasta ca

element.dataset.points

etc. Deci, în acest caz: this.dataset.points

Răspunsul #5

dacă vizezi un atribut de date într-un element Html,

document.dataset nu va funcționa

ar trebui să folosești

document.querySelector("html").dataset.pbUserId

sau

document.getElementsByTagName("html")[0].dataset.pbUserId