我有以下问题。如果我通过ajax生成anhor“load_more_btn”,那么单击功能(带有alert('test')的功能)将无法工作。为什么会出现这种情况以及如何解决这个问题?
<div id="content"></div>
<div id="load_more"></div>
<script type="text/javascript">
function getPhoto(paramType, param, page){
$.ajax({
url: "skrypt.php?paramType="+paramType+"¶m="+param+"&page="+page
}).done(function(data) {
$('#content').html(data);
var nextpage =page+1;
$('#load_more').html('<a href="#" id="load_more_btn" data-paramType="'+paramType+'" data-param="'+param+'" data-page="'+nextpage+'"=>Wczytaj więcej</a>');
});
}
$('#load_more_btn').click(function(){
alert('test');
});
</script>
最佳答案
Understanding Event Delegation
$(document).on("click","#load_more_btn",function(){
alert('test');
});
If you are click to newly added item, nothing would happen. This is because of the directly bound event handler that we attached on load time. Direct events are only attached to elements at the time the .on() method is called. In this case, add more button did not exist when document is loaded.
关于javascript - 加载内容后Ajax点击功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28321696/