How to pass an object to a dynamically created function call

I have a jQuery click event binding to thumbnails class = "thumnail":

$(".thumbnail").click(function(){
  var obj = new Object();
  obj.el = "imageEdit";
  obj.id = $(this).attr("id").replace("img_","");
  openDialogue(obj);
});

As you can see, I:

  • creating an obj object
  • calling the "openDialogue" function,
  • pass my obj object to openDialogue.

openDialogue will open a dialog box, and in the dialog box I am going to make an ajax call, get the path to the image and fill the dialog box with the image. This works great when the thumbnail is loaded on the update page, like on the form action page using php.

But I also need to fill in the thumbnail fields using js / jQuery when changing the selection field, and I think jQuery doesn’t cause a listen to a dynamically created element, such as a button or anchor or image (Am I wrong about that?).

When I change the product using the selection window, I fill out the thumbnails using jpgs thumbnails using this code:

$("#picture_row").empty();
$.each( data, function( k ) {
  var id;
  $.each( data[k], function( kk,vv ){
    if(kk == "id"){ 
      id = vv;
      var e = $('<div class="thumbBox" id="imageBox_'+id+'"></div>');
      $('#picture_row').append(e);
    }
    else if(kk == "file_name"){ 
      var obj = new Object();
      obj.el = "imageEdit";
      obj.id = id;

      var file_name = vv.replace(".jpg","_thumb.jpg");
      var img = $("<img class='thumbnail' id='img_"+id+"' src='../images/products/thumbs/"+file_name+"' onclick='openDialogue("+obj+");return false;' />");
      $("#imageBox_"+id).append(img);
    }
  })
});

As you can see, it is these lines that create a new image and try to add onclick:

var img = $("<img class='thumbnail' id='img_"+id+"' src='../images/products/thumbs/"+file_name+"' onclick='openDialogue("+obj+");return false;' />");
$("#imageBox_"+id).append(img);

For some reason, I cannot pass my obj object to a call to the dynamic create function:

onclick='openDialogue("+obj+");return false;'

I get this error:

Timestamp: 9/28/2013 7:04:33 PM
Error: SyntaxError: missing ] after element list
Source File: (domain and path)/management/
Line: 1, Column: 21
Source Code:
openDialogue([object Object]);return false;
+4
source share
1 answer

Instead of trying to embed event handling, use jQuery .on()

var img = $("<img class='thumbnail' id='img_"+id+"' src='../images/products/thumbs/"+file_name+"' />")
.on('click', function(){
  openDialogue(obj);
  return false;
}) ;
$("#imageBox_"+id).append(img);
+4
source

All Articles