Source: Ondragstart Attribute doesn’t appear when created dynamically.
En essayant de convertir la génération d’un élément TD
dans le DOM avec jQuery en code vanilla JS, je me suis heurté aux erreurs suivantes:
Uncaught TypeError: Cannot read property ‘getData’ of undefined
Uncaught TypeError: Cannot read property ‘setData’ of undefined
Le code jquery de départ:
1 |
$('<td id="' + i + '" title="' + i + '" class="is-cell" ondrop="drop_handler(event);" ondragover="dragover_handler(event);"></td>').appendTo('#row_' + x); |
Version vanilla JS/ES6
On commence par créer l’élément TD
:
1 |
let $cell = document.createElement('td'); |
Puis on lui assigne de multiples attributs (id
, title
, class
) (source: Setting multiple attributes for an element at once with JavaScript):
1 2 3 4 5 |
Object.assign($cell, { id: i, title: i, className: "is-cell" }); |
(pour n’ajouter qu’un seul attribut: $row.setAttribute("class", "is-row");
)
Mais pour ajouter des attributs relatifs à des événements (ondrop
, ondragover
, …), il faut utiliser la méthode addEventListener
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Ne fonctionne pas $cell.addEventListener("drop", dragndrop.drop_handler(event)); $cell.addEventListener("dragover", dragndrop.dragover_handler(event)); // Ne fonctionne pas $cell.ondrop = "drop_handler(event)"; $cell.ondragover = "dragover_handler(event)"; // Fonctionne $cell.ondrop = dragndrop.drop_handler; $cell.ondragover = dragndrop.dragover_handler; // Fonctionne (et c'est une meilleure façon de déclarer) $cell.addEventListener("drop", dragndrop.drop_handler); $cell.addEventListener("dragover", dragndrop.dragover_handler); |