Repeat Javascript when dom is updated with ajax

I tried for some time to solve this problem, which I now have, still do not use.

I have a main html file with a menu that loads content in div-ajax. The problem is that the downloaded content (the witch has the β€œnext” button to go to the next page with dynamic loading) does not work, so I had to add feedback on the function that I run on the parent page, Obviously, everything went wrong. because after clicking on some of the links I end the browser crash with more than 3000 requests for the same function ...

How can I make a function restart or listen for DOM changes? And .on does not work.

Script in the main file:

var din = function () {
    $('.dinMenu').on('click', 'a', function(event) {
        event.preventDefault();
        $('#dinContent').html('loading...');
        var $this = $(this);
        var module = $this.data("module");
        var folder = 'modules/module_' + module + '/';
        var href = $this.data("href");
        var url = folder + href;
        console.log(url);
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'html',
            cache: false
        }).done(function(data) {
            $('#dinContent').html(data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            $('#dinContent').html("Error!! File is not loaded");
        });
    });

    $(document).ready(function() {
     din();
    }); 

HTML:

 ...
 <li class="dinMenu"><a href="#" data-href="child.html" data-module="1">link</a></li>
 ...
 <section class="panel content" id="dinContent" >
   <!-- start panel specific content -->
 ...

and dynamic pages:

<footer class="subnav clearfix dinMenu">
  <a class="button next right" href="#" data-href="child.html" data-module="1">Next</a>
</footer>
<!-- end panel specific content -->
<script>
 din();
</script>

script child.html, , .

+4
2

$('.dinMenu').on('click', 'a', function(event) {

<li>, <body>:

$('body').on('click', '.dinMenu a', function(event) {

, , . , ajax.

+7

document.ready

$(document).ready(function(){
    $('.dinMenu').on('click', 'a', function(event) {
        event.preventDefault();
        $('#dinContent').html('loading...');
        var $this = $(this);
        var module = $this.data("module");
        var folder = 'modules/module_' + module + '/';
        var href = $this.data("href");
        var url = folder + href;
        console.log(url);
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'html',
            cache: false
        }).done(function(data) {
            $('#dinContent').html(data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            $('#dinContent').html("Error!! File is not loaded");
        });
    });
})

<script>

,

0

Source: https://habr.com/ru/post/1547786/


All Articles