Why doesn't the .click() not work in this instance?
Basically what this does is fadeIn pre-existing divs and then loads an image. When the image is loaded it then appends that into one of the pre-existing divs. Then it appends a new div with an id of xButton. Then later it $('#xButton').click() should hide the 3 divs. However it just doesn't work. If I change the click() to either #modalImage or #overlay, it works but just not for the #xButton. I would really like to figure out why its not working and how I should be doing this instead. Thanks.
$(function(){
$('#container a').click(function(e){
e.preventDefault();
var id = $(this).attr('href'),
img = new Image();
$('#overlay').fadeIn(function(){
$('#modalImage').fadeIn();
});
$(img).load(function(){
$(this).hide();
$('#modalImage').removeClass('loader').append(this);
$(this).fadeIn(function(){
var ih = $(this).outerHeight(),
iw = $(this).outerWidth(),
newH = ($(window).height()/10)*7,
newW = ($(window).width()/10)*7;
if (ih >= iw && ih >= newH) {
$(this).css('height',newH + 'px');
$(this).css('width', 'auto');
}
else if (ih >= iw && newH > ih) {
$(this).css('height', ih + 'px');
$(this).css('width', 'auto');
}
else if (iw > ih && iw >= newW) {
if ((newW / (iw / ih)) > newH) {
$(this).css('width', 'auto');
$(this).css('height', newH + 'px');
}
else {
$(this).css('width', newW + 'px');
$(this).css('height', 'auto');
}
}
else {
$(this).css('width', iw + 'px');
$(this).css('height', 'auto');
开发者_如何学Go }
var padW = ($(window).width() - $(this).outerWidth()) / 2,
padH = ($(window).height() - $(this).outerHeight()) / 2;
console.log (padH + ' ' + padW);
$(this).css('top', padH);
$(this).css('left', padW);
if($('#overlay').is(":visible") == true) {
ih = ih + 4;
$('<div id="xButton">x</div>').appendTo('#modalImage');
if (padH >= 0) {
$('#xButton').css('top', padH - 4).css('right', padW - 65);
}
else {
$('#xButton').css('top', '20px').css('right', padW - 65);
}
}
});
}).attr('src', id);
});
$('#xButton').click(function(){
$(this).hide();
$('#overlay').fadeOut(function(){
$('#modalImage img').css('top', '-9999px').remove();
$('#xButton').remove();
$('#modalImage').addClass('loader');
});
});
});
If you're setting an element dynamically you need to bind a listener, easiest way is using the jquery live() function:
http://api.jquery.com/live/
Looks like xButton is created after the click is attached in time. If you are going to do that, you need to make sure to set the xButton.click after xButton is actually created, not before. Or, you can use the live or delegate methods as described in the docs.
精彩评论