i’ve got this simple code
$(document).ready(function(){
$.ajax({
success: function(id) {
$('#ele').append('<a href="" onclick="deleteImg(id)">')
}
})
function deleteImg(id) {
foo...
}
}
but, when i click on the created href, i received this error
deleteImg is not defined
i have to put the deleteImg function out the $(document).ready() to working it
why?
many thanks!
When a string version of a function is called, like in
onclick="deleteImg(id)"it executes in the global context, meaning it’s basically looking for :But it isn’t there, it’s only defined in your
document.readyhandler’s scope. You’re better off binding the handler directly, like this:Or, store it in data on the element if it’s used for other things, like this:
Or, combine it all, and access it that way as well: