初始化动态创建的select2 [英] Initialising select2 created dynamically

查看:472
本文介绍了初始化动态创建的select2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个select2下拉菜单,为此我提供了一个匹配器功能.它是在初始页面加载时初始化的:

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.

现在,我还有其他下拉列表(动态创建的select元素(通过AJAX导入,即jQuery(match).load(url).这些额外的下拉列表不会被初始化为select2小部件,这是可以理解的,即使它们匹配)也是如此.原始的select2选择器.

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.

那么,如何告诉jQuery将这些动态创建的select元素视为需要初始化的select2项?我可以在匹配元素上设置某种监视"功能,以便每次将匹配元素添加到页面时都会启动select2初始化吗?

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?

我想起live()早在jQuery中引入的,如果我正确理解的话,它支持在创建匹配元素之前将它们匹配.我从未使用过该功能,现在似乎已弃用.但这确实像我想要的东西.

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.

这是一个WordPress插件,目前使用jQuery v1.11.2.

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

推荐答案

您可以尝试使用DOMNodeInserted并查找select或您为其分配的类

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

演示

Demo

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

更新

DOMNodeInserted

已弃用 此功能已从Web标准中删除.尽管某些浏览器可能仍支持它,但是它正在被删除.避免使用它,并尽可能更新现有代码;

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;

建议的方法应为 MutationObserver

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>

这篇关于初始化动态创建的select2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆