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:
$(function(){
loadSpan();
});
But I want to generate the code after clicking the button.
>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">