toggle() not working for content loaded with ajax?

2019-01-20 17:08发布

问题:

$('.slideArrow').toggle(function (event) {
  //some code
}, function (event) {
    //some code
});

This works fine for content which are loaded on page-load.But the same function does not work for content loaded with ajax.It just does not intercept the click.

What should I do?

In an other scenario,i faced a same problem(not for toggle,for click) and sorted it this way.I dont know what to do for toggle?

$('.common-parent').on('click','.target-of-click',function(){
//some code
})

回答1:

The flag method :

var flag = false;

$(document).on('click', '.slideArrow', function(event) {
    if (flag) {
        // do one thing
    }else{
        // do another thing
    }
    flag = !flag;
});

the data method

$(document).on('click', '.slideArrow', function(event) {
    if ( $(this).data('flag') ) {
        // do one thing
    }else{
        // do another thing
    }

    $(this).data('flag', !$(this).data('flag'));
});