I have a bit of jquery that makes an ajax request to a script and returns some json results.
These results are then parsed and a little image gallery is created.
This is then added to my form.
That bit all works perfectly….
The problem I have is that I am trying to trigger an event to the images so that when you click an image I can do some more processing…. But I just cannot get the onclick to work…
If anyone has any pointers I would be very grateful.
$('.imgSel').click(function()
{
alert("I WORK!!!!");
});
$("#mydiv").change(function(){
{
var url = "ajax_pics.php";
$.ajax({
type: "GET",
url: url,
error: function(data){
console.log("could not get get pics");
},
success: function(data){
console.log(data);
var pics = jQuery.parseJSON( data );
$("#imageResultsDiv").remove();
var imageResults ='<label>Image</label><div id="currImg"></div>';
imageResults += "<div style='clear:both'></div><ul>";
imageResults += "<div id='imageResultsDiv'><ul>";
for(var i in pics)
{
imageResults +="<li>";
imageResults +="<img class='imgSel' id='"+pics[i].filename+"' src='"+pics[i].image+"' title='"+pics[i].summary+"'>";
imageResults +="<br/><small>"+pics[i].title+"</small>";
imageResults +="</li>";
}
imageResults +="</ul>";
$('#picsplaceholder').before(imageResults);
}
});
});
If I understood you right you are dynamically adding elements to the DOM.
In that case you can’t use the standard click bindings as they only vind to elements already existing in the DOM.
Try to use on(), which is the preferred method since jQuery 1.7:
You have to use the closest static element to bind to and then specify the sub-element you want the click event to apply to. I think in your case
$('#mydiv')is the closest static element.If you happen to use an older version of jQuery use delegate() instead.
See this post for more details on the different binding methods and when they were added and who replaced which and when.