简体   繁体   中英

HTML button calling Event listener not working HTML and JS

I have made a list of items with JSON and JS and I need to be able to delete them.

function deleteList(){
  document.querySelector('#delete').addEventListener('click', (e) => {
    document.querySelector('#exerciseList').innerHTML = '';
  });
}

Here is my HTML button:

<button onclick="deleteList()" id="delete">Clear List</button>
<section id="exerciseList"></section>

are these just not connected right?

You either add an event listener or the onclick attribute, so

 function deleteList() { document.querySelector("#exerciseList").innerHTML = ""; }
 <button onclick="deleteList()" id="delete">Clear List</button> <section id="exerciseList">list</section>

or, recommended:

 document.querySelector("#delete").addEventListener("click", e => { document.querySelector("#exerciseList").innerHTML = ""; });
 <button id="delete">Clear List</button> <section id="exerciseList">list</section>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM