JQuery - .hover() after .load()ing the image and .append()ed to .find()div
Hi :) I've ran into a bit of a trouble.
(short-form: whenever the page is populated by .each() the .hover and .click functions wont work. althought if i populate the the page manually .hover()s and .click()s work like a charm)
formerly i had this:
<imgThumb imgn="1">thumb</imgThumb>
<imgThumb imgn="2">thumb</imgThumb>
and this,
$("imgt").hover(
function () {
var imgN = $(this).attr("imgn");
var img = new Image();
$(img).load(function(){
$(this).hide();
$("#mainRight_PubSpot").append(this);
$(this).fadeIn();
}
)
.attr("src","image/thumb"+imgN+".jpg");
},开发者_运维百科
function () {
$("#mainRight_PubSpot").find("img:last").remove();
}
);
worked like a charm, no biggies. Until i replaced <imgThumb>
with this:
$.get('gallery.php',
function(data){
var obj = jQuery.parseJSON(data);
//alert(obj)
$.each(obj,function(index, value){
//alert(this);
var n = index+1;
//alert(""+n+" "+index);
var nimg = new Image();
$(nimg).load(function() {
$(this).hide();
/*$("#galImg").css({
'width':50,
'height':50
});*/
$("#mainLeft_imgHold").append("<imgt imgn="+n+"></imgt>")
$("#mainLeft_imgHold").find('imgt:last').append(this);
$(this).fadeIn();
}).attr({
src:""+this,
imgn:""+n,
id:"imgThumb"
});
});
}
);
Now the images load without a sweat wahtsoever althought the .hover and .click functions wont work.
Anyone has a hint on to what might be causing all this commotion?
If you are loading elements after pageload (asynchronously, etc.) you need to attach handlers like hover
and click
with the .live()
method.
Here's a link to the API page: http://api.jquery.com/live/
Note that .live()
doesn't support all of jQuery's smarter listeners (like hover
) out of the box. You may end up having to instantiate the mouseover
and mouseout
manually:
$("imgt").live('mouseover', function(){...
$("imgt").live('mouseout', function(){...
There are ways around this by creating your own listeners, but that's another answer for another question.
The reason it fails is because when you add new items to a page with Javascript, the DOM changes and the Javascript needs to be re-rendered.
http://api.jquery.com/live/ can fix this for you, or you can try implementing your own method of checking if the DOM has changed with .change()
handler.
精彩评论