我有这段代码:
$("#top").on('click',function(){
alert('I am here');
$('html, body').animate({scrollTop:200}, 'slow');
return false;
});
当我点击按钮(由jquery生成,但在点击代码之前)
html += "<p><a href='javascript:;' id='top'>Back to Top</a></p>";
警报未出现。我也试过这个:
$("#top").click(function(){
alert('I am here');
$('html, body').animate({scrollTop:200}, 'slow');
return false;
});
我已尝试将此代码移入页脚,但是没有做任何事情,此代码包含在$(document).ready(function(){
我不知道我做错了什么。
答案 0 :(得分:4)
事件处理程序仅绑定到当前选定的元素;它们必须存在于您的代码进行事件绑定调用时的页面上。
在动态创建元素时,您需要使用Event Delegation委托事件方法来使用.on()。
即
$(document).on('event','selector',callback_function)
实施例
$(document).on('click', "#top", function(){
//Your code
});
代替document
,您应该使用最接近的静态容器以获得更好的性能。