JQuery event handler when select element is loaded

前端 未结 7 1723
清歌不尽
清歌不尽 2021-01-03 01:53

Is there an event handler to use in JQuery when a DOM select element has finished loading? This is what I want to achieve. It is working with other events e

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 02:48

    My solution is a little similar to the posters above but to use the observer (pubsub) pattern. You can google for various pub sub libraries out there or you could use jQuery's custom events. The idea is to subscribe to a topic / custom event and run the function that attach the event. Of course, it will be best to filter out those elements that have been initialize before. I havent test the following codes but hopefully you get the idea.

    function attachEventsToSelect(html) {
        if (!html) { // html is undefined, we loop through the entire DOM we have currently
            $('select').doSomething();
        } else {
            $(html).find('select').doSomething(); // Only apply to the newly added HTML DOM
        }
    }
    
    $(window).on('HTML.Inserted', attachEventsToSelect);
    
    // On your ajax call
    $.ajax({
        success: function(htmlResponse) {
            $(window).trigger('HTML.Inserted', htmlResponse);
        }
    });
    
    // On your DOM ready event
    $(function() {
        $(window).trigger('HTML.Inserted'); // For the current set of HTML
    });
    

提交回复
热议问题