jQuery does not execute on dynamically loaded content, even on a click events

喜你入骨 提交于 2019-12-11 06:45:44

问题


I have two document.ready() functions. The first loads content into div#header. The second one performs a hide function and then a toggle function on the newly loaded content. I am not sure if this is a queueing issue or something, but not even the alert() below is executed when I click the loaded content. Thanks.

<script type="text/javascript">
$(document).ready(function() {
     $("#header").load("/documents/collegeradioheader.txt");
});
</script>
<script type="text/javascript">
 $(document).ready(function() {
    $(".hideme").hide(); 
    $(".slick-toggle").click(function() {
        alert('hi');
        $(this).parent().next('div').slideToggle('fast');       
    });
});
</script>

Edit: simplified code


回答1:


Although the live is a working solution, there is an complete event in the AJAX load that fires when the load has finished.

<script type="text/javascript">
$(function() {
    $("#header").load("/documents/collegeradioheader.txt", function() {
        $(".hideme").hide(); 
        $(".slick-toggle").click(function() {
            alert('hi');
            $(this).parent().next('div').slideToggle('fast');       
        });
    });
});
</script>



回答2:


The click binding is probably happening before the .load is finished. Try replacing your .click with a .live version:

$(".slick-toggle").live('click', function() {
    alert('hi');
    $(this).parent().next('div').slideToggle('fast');
});


来源:https://stackoverflow.com/questions/4954430/jquery-does-not-execute-on-dynamically-loaded-content-even-on-a-click-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!