2013-07-07 113 views
1

我試圖使用jQuery追加.thumb到另一個最後一個div點擊.button懸停事件不工作

這當jQuery函數:

$('.thumb').hover(function() { 
    $(this).find('.close').fadeIn(); 
}, function() { 
    $(this).find('.close').fadeOut(); 
}); 
$('.close').click(function() { 
    $(this).parent().fadeOut('slow'); 
}); 
$('.button').click(function() { 
    $html = '<div class="thumb">'; 
    $html += '<img src="http://findicons.com/files/icons/1979/social/50/wordpress.png" />'; 
    $html += '<div class="close">X</div>'; 
    $html += '</div>'; 
    $('.box').append($html); 
}); 

http://jsfiddle.net/UfyQq/

我使用此代碼所面臨的障礙是附加的div不服從懸停事件或使用點擊功能.close

我真的很感謝這裏的一些幫助,謝謝!

+0

我認爲瀏覽器在開始時爲每個元素設置了事件,並且如果在加載頁面之後追加元素,它不能正常工作。創建新元素或將鼠標懸停在創建元素的水平後設置懸停事件 –

+0

我使用了單獨的組件,包含懸停事件,點擊功能和'$ .ajax',感謝回覆! – UserNaN

回答

2

問題是附加事件偵聽器時附加內容不存在。在父元素上使用jQuery's .on()來解決這個問題。

check this working jsFiddle

$('.box').on('mouseenter','.thumb',function() { 
    $(this).find('.close').fadeIn(); 
}); 

$('.box').on('mouseleave','.thumb',function() { 
    $(this).find('.close').fadeOut(); 
}); 
2

你必須使用委託:

DEMO

$('.box').on({ 
    mouseenter: function() { 
     $(this).find('.close').fadeIn(); 
    }, 
    mouseleave: function() { 
     $(this).find('.close').fadeOut(); 
    } 
}, '.thumb'); 

$('.box').on('click','.close',function() { 
    $(this).parent().fadeOut('slow'); 
}); 
+0

如何使用'.close'上的點擊功能 – UserNaN

+0

查看更新後的答案並查看DEMO,使用代表團 –

+0

解決問題的好方法,謝謝! – UserNaN

0

阿爾特:

$('.thumb').hover(function() { 
    $(this).find('.close').fadeIn(); 
}, function() { 
    $(this).find('.close').fadeOut(); 
}); 
$('.close').click(function() { 
    $(this).parent().fadeOut('slow'); 
}); 
$('.button').click(function() { 
    $html = '<div class="thumb">'; 
    $html += '<img src="http://findicons.com/files/icons/1979/social/50/wordpress.png" />'; 
    $html += '<div class="close">X</div>'; 
    $html += '</div>'; 
    $('.box').append($html); 
}); 

爲:

$('.thumb').hover(function() { 
    $(this).find('.close').fadeIn(); 
}, function() { 
    $(this).find('.close').fadeOut(); 
}); 
$('.close').click(function() { 
    $(this).parent().fadeOut('slow'); 
}); 
$('.button').click(function() { 
    $html = '<div class="thumb">'; 
    $html += '<img src="http://findicons.com/files/icons/1979/social/50/wordpress.png" />'; 
    $html += '<div class="close">X</div>'; 
    $html += '</div>'; 
    $('.box').append($html); 
    $('.thumb').hover(function() { 
    $(this).find('.close').fadeIn(); 
}, function() { 
    $(this).find('.close').fadeOut(); 
}); 
$('.close').click(function() { 
    $(this).parent().fadeOut('slow'); 
}); 
}); 

這會再次附加事件。

+0

這會將'.close'點擊事件多次附加到現有的按鈕上。 –

+0

嗯,我知道,但沒有內存交換cos覆蓋以前的事件監聽器。 - 確實有很多美麗的解決方案。 – JonnieJS

+0

是的,但我附上'$ .ajax'不應該被用來解決我的問題。謝謝! – UserNaN