Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use the class from added code in the jquery function

I create html code with jquery.

<span id="myspan">aa</span>
<input id="btn" type="button" value="click">

Now I want to call a function created by clicking on the code class.

function loadSpan()
{
var _html = "<a class=\"addItem\">test</a>";
$('#myspan').html(_html);
}
$(function(){
$('#btn').click(function(){
loadSpan();
});
$('.addItem').click(function(){
alert("OK");
});
})

but is not working. I testing this code, and working:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(function(){
loadSpan();
});

But I want to generate the code after clicking the button.

test code

>Solution :

Use event delegation on the span element to handle events on dynamically created elements.

function loadSpan() {
  var _html = "<a class=\"addItem\">test</a>";
  $('#myspan').html(_html);
}
$('#btn').click(function() {
  loadSpan();
});
$('#myspan').on('click', '.addItem', function() {
  console.log("OK");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myspan">aa</span>
<input id="btn" type="button" value="click">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading