A button click fires my function that fetches image data via an AJAX-call:
$("#toggle_album").click(function () {
album_id = $("#album_id").val();
$.post('backend/load_album_thumbnails.php', {
id: album_id
}, function(xml) {
var status = $(xml).find("status").text();
var timestamp = $(xml).find("time").text();
$("#album_thumbs_data_"+album_id+"").empty();
if (status == 1) {
var temp = '';
var output = '';
$(xml).find("image").each(function(){
var url = $(this).find("url").text();
temp = "<DIV ID=\"thumbnail_image\"><A HREF=\"javascript:void(nul开发者_Python百科l);\" CLASS=\"overlay\">[img-tag with class="faded" goes here]</A></DIV>";
output += temp;
});
$("#album_thumbs_data_"+album_id+"").append(output);
} else {
var reason = $(xml).find("reason").text();
var output = "<DIV CLASS=\"bread\">"+reason+"</DIV>";
$("#album_thumbs_data_"+album_id+"").append(output);
}
$("#album_thumbs_"+album_id+"").toggle();
});
});
The data is returned in XML format, and it parses well, appending the data to an empty container and showing it;
My problem is that my image overlay script:
$("img.faded").hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
});
... stops working on the image data that I fetch via the AJAX-call. It works well on all other images already loaded by "normal" means. Does the script need to be adjusted in some way to work on data added later?
I hope my question is clear enough.
Okay, apparantly I hadn't googled it enough. Surfing my own question here on stackoverflow pointed me to other questions, which pointed me to the JQuery live() function: live().
However, it does not work on hover(), so I rewrote the script to use mouseover() and mouseout() instead:
$("img.faded").live("mouseover",function() {
$(this).animate({"opacity": "1"}, "fast");
});
$("img.faded").live("mouseout", function() {
$(this).animate({"opacity": "0.5"}, "fast");
});
... and now it works flawlessly even on the content I fetch from the AJAX-call.
Sorry if anyone has started writing an answer already.
You have to bind the new events each time you add a DOM element to the page.
There is a built-in function in jquery called live that does that for you.
I noticed you add the images from your xml; you can add there the new binds too.
$(xml).find("image").each(function(){
//this actually creates a jquery element that you can work with
$('my-img-code-from-xml-goes-here').hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
}
//i did all my dirty stuff with it, let's add it where it belongs!
).appendTo($('some-already-created-element'));
});
EDIT: corrected a wrong sentence.
精彩评论