由于 JSON 的负载,该脚本可能无法工作:
$(function(){
$('#fresh-button').click(function(){
$('.blackout').fadeIn(300);
$('.fresh-div').fadeIn(300);
setTimeout(function(){
$('.blackout').fadeOut(300);
$('.fresh-div').fadeOut(300);
},500);
})
})
我有一个带有 id=fresh-button
的 div,在从 $.getJSON 附加它之前它并不存在:
$.getJSON('fresh_posts.php',function(data){
data.freshposts.forEach(function(post){
var post = '<div id="fresh-button"><div>';
$('.main').append(post);
})
})
最佳答案
使用事件委托(delegate)绑定(bind)点击处理程序,但您还应该将 id
更改为 class
,因为 id
必须是唯一的。请参阅 jquery .on()
function 的文档有关事件委托(delegate)的信息。
$('.main').on('click', '.fresh-button', function(){
...
var post = '<div class="fresh-button"><div>';
关于javascript - 脚本无法使用不存在的 ID,除非 $.getJSON 附加它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30678788/