javascript - preventDefault( ) on appended html does not work. why? -


the title self explanatory. i'm appending html document in ajax call , prevent default event when click in <a> tag generated function. here's code:

$.ajax({ type: 'get', url: "/api/search/info/" +id, accepts: 'application/json' }).then(function(data, status, xhr) {   $(".book-results #results").append("<a class='bookitem' href='b"+data.value+"'>add book</a>"); }, showerr); 

inside same javascript file (but not within ajax function ), have listener:

$(".bookitem").click(function(event) {   event.preventdefault();   console.log("hello"); }); 

when trigger ajax event, .book-results #results gets populated, when click <a> tag default event gets triggered. there way make listener work? if so, how?

you can't apply event listener before element trying attach listener exists. $(".bookitem").click(function(event) {...}); bind elements class of bookitem exist @ time.

if dynamically adding elements, need either attach event handlers elements after create them or, better, use delegation.

for delegation attach event handler parent element, example:

$(".book-results #results").on("click",".bookitem", function(event) {     // handler goes here. }); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -