初始化动态创建的select2

我有一个select2下拉列表,我提供了一个匹配器function。 它在初始页面加载时初始化为:

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

这适用于初始页面加载。

现在,我有额外的下拉菜单( select动态创建的元素(通过AJAX拉入,即jQuery(match).load(url) 。这些额外的下拉菜单不会像select2小部件那样初始化,这是可以理解的,即使它们匹配原始的select2选择器。

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

我记得前一段时间在jQuery中引入的live() ,如果我理解正确的话,它会在创建之前支持匹配元素。 我从未使用过该function,现在看来已弃用了。 但它确实感觉像我正在寻找的那种东西。

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

您可以尝试使用DOMNodeInserted并查找select或您正在分配它们的类

演示

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

更新

DOMNodeInserted

已弃用此function已从Web标准中删除。 虽然有些浏览器可能仍然支持它,但它正在被删除。 如果可能,请避免使用它并更新现有代码;

使用MutationObserver建议的方法就是这样的

 $(function() { $("button").on("click", function() { $("#dynamic-container").append($("")); }); // 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(); } }); 
    

我最近遇到了类似的情况,但是以一种非常平常的方式做到了:

 $(document).ready(function() { //function to initialize select2 function initializeSelect2(selectElementObj) { selectElementObj.select2({ width: "80%", tags: true }); } //onload: call the above function $(".select-to-select2").each(function() { initializeSelect2($(this)); }); //dynamically added selects $(".add-new-select").on("click", function() { var newSelect = $(""); $(".select-container").append(newSelect); initializeSelect2(newSelect); }); }); 
    

这个对我有用

 

我的工作类似于roshan的解决方案,但没有在函数中传递select对象。 这是针对ajax调用的表输出。

 $(document).ready(function() { function initSelect2() { $("[id^='DDAlertFreq']").select2({ minimumResultsForSearch: Infinity, allowClear: false, theme: "bootstrap" }); }; //define the dropdown and set to variable var DDAlertFrequency = '' function RetrieveUserAlerts(uid) { $.ajax({ url: 'SavedSearches.asmx/LoadUserAlerts', dataType: 'json', method: 'post', data: { userid: uid }, success: function (data) { var tbl = $("#tblAlerts > tbody"); tbl.empty(); $.each(data, function () { userAlert.alert_idx = this['alert_idx']; userAlert.Name = this['Name']; userAlert.price_alert_low = this['price_alert_low']; userAlert.alert_frequency = this['alert_frequency']; userAlert.alert_max_per_day = this['alert_max_per_day']; userAlert.alert_to_email = this['alert_to_email']; userAlert.alert_to_sms = this['alert_to_sms']; userAlert.active = this['active']; userAlert.alert_start_date = moment(this['alert_start_date']).format("MM/DD/YY"); userAlert.alert_end_date = moment(this['alert_end_date']).format("MM/DD/YY"); userAlert.OpenSectionID = this['OpenSectionID']; // modify the dropdown to assign unique id and match selection var selectAlert = DDAlertFrequency.replace("DDAlertFreq", "DDAlertFreq_" + userAlert.alert_idx).replace('"' + userAlert.alert_frequency + '"', '"' + userAlert.alert_frequency + '" selected'); var tblRow = '' + userAlert.Name + '' + '' + '' + '' + '' + '' + '' + selectAlert //modified Select2 dropdown + '' + '' + '' + userAlert.alert_start_date + '' + userAlert.alert_end_date + '' + '' + '' tbl.append(tblRow); initSelect2(); //call the function to initialize all Select2 dropdowns created }); }, error: function (err) { console.log('Error (RetrieveUserAlerts): ' + JSON.stringify(err, null, 2)); } }); }; 

很抱歉留下无关紧要的东西 – 我评论了感兴趣的领域。 希望这有助于他人!