Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

jquery - Initialising select2 created dynamically

I have a select2 drop-down for which I provide a matcher function. It is initialised like this on initial page load:

jQuery(document).ready(function() {
    jQuery(".my_select2").select2({
        matcher: function(term, text) {...}
    });
});

That works find on initial page load.

Now, I have additional drop-downs (select elements created dynamically (pulled in via AJAX, i.e. jQuery(match).load(url). These additional drop-downs do not get intialised as select2 widgets, which is understandable, even though they match the original select2 selector.

So, how can I tell jQuery to treat these dynamically-created select elements as select2 items that need to be initialised? Can I set some kind of "watch" on matching elements so the select2 initialisation kicks in every time a matching element gets added to the page?

I recall live() being introduced in jQuery some time ago, that supported matching elements before they are created, if I understood it correctly. I never used that feature, and it now appears deprecated. But it does feel like the kind of thing I am looking for.

This is for a WordPress plugin, which uses jQuery v1.11.2 at present.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can try with DOMNodeInserted and look for select or the class you're assigning them

Demo

$('body').on('DOMNodeInserted', 'select', function () {
    $(this).select2();
});

Update

DOMNodeInserted

Deprecated This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible;

The suggested method would be something like this with MutationObserver

$(function() {
  $("button").on("click", function() {
    $("#dynamic-container").append($("<select><option>test</option><select/>"));
  });

  // select the target node
  var target = document.getElementById('dynamic-container');

  if (target) {
    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
      //loop through the detected mutations(added controls)
      mutations.forEach(function(mutation) {
      //addedNodes contains all detected new controls
        if (mutation && mutation.addedNodes) {
          mutation.addedNodes.forEach(function(elm) {
          //only apply select2 to select elements
            if (elm && elm.nodeName === "SELECT") {
              $(elm).select2();
            }
          });
        }
      });
    }); 
    
    // pass in the target node, as well as the observer options
    observer.observe(target, {
      childList: true
    });

    // later, you can stop observing
    //observer.disconnect();
  }
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>


<button>Add new select</button>
  <div id="dynamic-container">

  </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...