How can I make my event listener work on inserted HTML?
I insert <li id="test">Titre : test<input type="button" id="del" value="X"><br>Texte : </li>
on my list, but my event listener only works on the button named "work", which is created in the HTML page.
I want to call the function clickHandlerRem
by clicking on the new button in the list.
Image:
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="libs/css1.css" rel="stylesheet">
<script src="/script1.js"></script>
</head>
<body>
<form>
Ajouter une note
<input type="text" id="oTitleInput" placeholder="Entrez un titre" />
<input type="button" id="bdel" value="Supprimer"/>
<input type="text" id="oTextInput" placeholder="Entrez une note ici" />
<input type="button" id="binput" value="Ajouter"/>
<div class="divlist">
<ul class="notelist" id="notelist">
</ul>
</div>
</form>
<input type="button" id="del" value="work"/>
</body>
</html>
And my JavaScript code:
function clickHandler(e) {
addnote();
}
function clickHandlerDel(e) {
var oTitle = document.getElementById("oTitleInput").value;
delnote(oTitle);
document.getElementById("oTitleInput").value = '';
document.getElementById("oTextInput").value = '';
}
function clickHandlerRem(e) {
var oTitle = "test";
delnote(oTitle);
}
function addnote() {
var oTitle = document.getElementById("oTitleInput").value;
document.getElementById("oTitleInput").value = '';
var oText = document.getElementById("oTextInput").value;
document.getElementById("oTextInput").value = '';
localStorage.setItem(oTitle, oText);
affnote();
}
function affnote() {
var node = document.getElementById("notelist");
while (node.firstChild) {
node.removeChild(node.firstChild);
}
for (var i = 0, len = localStorage.length; i < len; i++) {
var key = localStorage.key(i);
var value = localStorage[key];
var html = "<li id=\"" + key + "\">Titre : " + key + "\<input type=\"button\" id=\"del\" value=\"X\"\/\><br />Texte : " + value + "</li>";
document.querySelector('#notelist').innerHTML += html;
}
}
function delnote(keyname) {
localStorage.removeItem(keyname);
affnote();
}
function main() {
affnote();
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#binput').addEventListener('click', clickHandler);
document.querySelector('#bdel').addEventListener('click', clickHandlerDel);
document.querySelector('#del').addEventListener('click', clickHandlerRem);
main();
});
Javascript will not reattach event handlers after you create a new DOM element. You will have to add the event handler to your new element manually:
Run
document.querySelector('#del').addEventListener('click', clickHandlerRem);
at the end of affnote()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.