I want to add an event handler to a dynamically generated list. I need to prevent the default action on the list item, and just console log "clicked". An example of what I'm trying to do is below:
$("#make-list").click(function() {
var mainList = document.getElementById("the-list");
for(var i = 0; i < 6; i++) {
mainList.innerHTML += "<li class='list-item'><a class='the-list__link' href='https://example.com'>Click ME!</a></li>"
};
})
$(".the-list__link").on("click", function() {
e.preventDefault();
console.log("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="make-list">MAKE LIST</button>
<ul id="the-list"></ul>
These answers:
Explain that due to how the .click()
event is delegated, to use .on()
method. I'm doing that. Why is it not working?