简体   繁体   English

如何将动态DOM元素转换为Select2?

[英]How to turn dynamic DOM element into Select2?

I have the following HTML code: 我有以下HTML代码:

<input type="text" id="condition_value_1">
<span class="click_me">Click Me</span>

I am replacing the #condition_value_1 element with a SELECT type as follow and trying to turn the recently SELECT into a Select2: 我正在用SELECT类型替换#condition_value_1元素,如下所示,并尝试将最近的SELECT转换为Select2:

$(function() {
  $('.click_me').click(function(ev) {
    var condition_value_1 = $('#condition_value_1');
    var select_html = '<select name="condition_value_1" id="condition_value_1"></select>';
    condition_value_1.replaceWith(select_html);

    $('body').on('DOMNodeInserted', '#condition_value_1', function() {
      $(this).select2({
        placeholder: 'Start typing ...',
        tags: true
      });
    });
  });
});

But is not working since the element keep as a normal HTML Select type and doesn't turn into a Select2. 但由于元素保持为普通的HTML Select类型并且不会变成Select2,因此无效。 Here is a Fiddle for you to play with. 这是一个让你玩的小提琴 I am using jQuery 1.12.4 and Select 4.0.3. 我使用的是jQuery 1.12.4和Select 4.0.3。

How do I turn a dynamic element into a Select2 element? 如何将动态元素转换为Select2元素? Any help? 有帮助吗?

Seems to work for me if not using DOMNodeInserted event binding. 如果不使用DOMNodeInserted事件绑定,似乎对我DOMNodeInserted

It's fair to assume the element has been added to the DOM when the replaceWith() method is called. 假设在调用replaceWith()方法时replaceWith()元素添加到DOM中,这是公平的。

JS Fiddle updated JS Fiddle更新

$(function() {
  $('.click_me').click(function(ev) {
    var condition_value_1 = $('#condition_value_1');
    var select_html = '<select name="condition_value_1" id="condition_value_1"></select>';
    condition_value_1.replaceWith(select_html);

    $('#condition_value_1').select2({
        placeholder: 'Start typing ...',
        tags: true
      });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM