Apply jquery function to ajax content

前端 未结 2 1339
栀梦
栀梦 2021-01-07 02:14

I want to apply this function to content which is loaded by ajax. Thing is, the function is not working on such content. Is there somehow a workaround for this each-function

相关标签:
2条回答
  • 2021-01-07 02:54

    Building on what achitaka-san said, with the latest jQuery you can just do...

    $(document).on('ready ajaxComplete', function() {
        // ...attach your events/plugins here
    });
    

    Which, I think is a bit cleaner and easier to follow/extend if you ever needed to. You need to be careful about creating loops though (for example if you fire some AJAX calls in your 'ready' handler!).

    0 讨论(0)
  • 2021-01-07 02:55

    I faced the same problem recently. Most of plugins need to be applied to elements by calling them in $(document).ready(), I wanted to call the same function not only for content which was there just after the document was loaded, but also for those elements which arrived by Ajax call later.

    After googling a while I found two types of recommendations: 1. To bind to final event of every ajax call. 2. To bind to some element specific event, (like focus()) to run your code.

    In the first case you need to take care about it in your ever ajax call. The second did not worked for all cases well.

    So my solution is to call the same function from $(document).ready() and $(document).ajaxSuccess(). In this case I need to prevent one and the same manipulation to happen to the same control twice. SO I used a special class I am applying to all visited elements.

    function doOnReady() {
        $(":input[data-autocomplete]").each(function () {
            //Check wether allready visited
            if (!$(this).hasClass('visited-by-on-ready')) {
    
                //Do your staff
                $(this).autocomplete({
                    source: $(this).attr("data-autocomplete"),
                });
                //mark as visited
                $(this).addClass('visited-by-on-ready');
            }
        });
    }
    
    $(document).ready(doOnReady);
    $(document).ajaxComplete(doOnReady); 
    
    0 讨论(0)
提交回复
热议问题