javascript - How to assign click event for dynamically added span element? -


this question has answer here:

html:

<div class="testspandiv"></div> 

javascript:

  $(document).ready(function () {       $('.testspandiv').append('<span id="testspan">hello</span>');   }    $('#testspan').on('click', function(){       $(this).parent().remove();   }); 

event not firing while giving click span element added dynamically. event firing if span element statically added html. can give suggestion on it.

i tried below also, not working.

  $('#testspan').on('click', '.testspandiv', function(){       $(this).parent().remove();   }); 

you need use this:

  $('.testspandiv').on('click', '#testspan', function(){   // ^^ parent div             ^^ element in want bind function       $(this).parent().remove();  }); 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

python 3.5 - Pyqtgraph string in x tick -