tags:

views:

74

answers:

5

hi all!

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!

+3  A: 
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.

Dean Harding
+7  A: 

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...
   }
});
Nick Craver
nice answer....+1
Night Shade
works better now!thanks to all! :-)
Roberto
+1, (*but you need to escape your quotes or use single ones on the outside.., just nitpicking ..*)
Gaby
@Gaby: Good catch, thought the coloring was off earlier but didn't process, fixed now
Nick Craver
+1  A: 

Because of the scope. deleteImg is declared inside your anonymous ready() function and is not defined outside it.

RC
+1  A: 

deleteImg is local to the function closure you're feeding $(document).ready(). Try this instead:

window.deleteImg = function(id) {
  foo...
}
Julian Aubourg
+1  A: 

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.

eje211