function out $('document').ready()
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 开发者_如何学Pythonerror
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 :
window.deleteImg
But it isn't there, it's only defined in your document.ready
handler's scope. You're better off binding the handler directly, like this:
$(function(){
$.ajax({
success: function(id) {
$("<a href='#'></a>").click(function() {
deleteImg(id);
}).appendTo('#ele');
}
})
function deleteImg(id) {
//foo...
}
});
Or, store it in data on the element if it's used for other things, like this:
$("<a href='#'></a>").data('id', id).click(function() {
deleteImg($.data(this, 'id'));
}).appendTo('#ele');
Or, combine it all, and access it that way as well:
$(function(){
$.ajax({
success: function(id) {
$("<a href='#'></a>").data('id', id).click(deleteImg).appendTo('#ele');
}
})
function deleteImg() {
var id = $.data(this, 'id');
//foo...
}
});
function foo() {
function bar() { alert("Hello!"); }
var baz = 123;
}
In the above snippet, the bar
function is a local function to foo
. It's just the same as how the baz
variable is a local variable to the foo
function: you can't access baz
outside of foo
and you can't access bar
outside of foo
in exactly the same way.
Because of the scope. deleteImg
is declared inside your anonymous ready()
function and is not defined outside it.
deleteImg is local to the function closure you're feeding $(document).ready(). Try this instead:
window.deleteImg = function(id) {
foo...
}
Also, you could use jQuery to add the click event.
$.ajax({
success: function(id) {
$('#ele').append('<a href="" class="deleteImg">');
$('.deleteImg').click(function() {
window.deleteImg($(this).id);
});
}
})
It may look a bit overkill now, but if the code gets more complicated, or even the way it is now, it's usually a good idea to keep to Javascript and the HTML apart as much as possible. That's one of the main reasons to use jQuery in the first place.
精彩评论