javascript - 加载内容后Ajax点击功能不起作用

标签 javascript jquery ajax

我有以下问题。如果我通过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+"&param="+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/

相关文章:

javascript - jquery ajax 调用和 j_security 重定向

javascript - 变量内的代码在没有被调用的情况下触发?

javascript - 为什么有对象时控制台中显示 'Null is not an Object'?

javascript - 未计算 div 的外部高度

ajax - jQuery.ajax 处理继续响应 : "success:" vs ".done"?

jquery - 如何在 Rails 上启用 Turbolinks 的情况下通过 AJAX 正确渲染部分内容?

javascript - 当 child 获得焦点时触发模糊事件

javascript - 在 AngularJS 中的 View 之间保留 GoogleMaps map 对象

jquery - imgAreaSelect 不隐藏在模式关闭时,或随页面滚动

javascript - 清除间隔不起作用