简体   繁体   English

ajax后不再工作的jQuery select2

[英]jquery select2 after ajax not working anymore

I have a simple select2 control on my site placed in a div. 我在div上的站点上有一个简单的select2控件。 When the site loads, everything works fine. 网站加载后,一切正常。 However, if the html content of the div "simpleDiv", where the Select2 is placed, is loaded with Ajax, the Select2 is not showing the results anymore when triggered. 但是,如果将Select2所在的div的simpleDiv的html内容加载了Ajax,则Select2在触发时不再显示结果。 That means, in this case the Select2 data is got from the Server, but never shown in the Select2. 这意味着,在这种情况下,Select2数据是从服务器获取的,但从未在Select2中显示。 And this all happens just when the "simpleDiv" html content is loaded with Ajax. 这一切仅在Ajax加载“ simpleDiv” html内容时发生。 Otherwise, everything works fine. 否则,一切正常。

Can anyone help, please? 有人可以帮忙吗?

<div id='simpleDiv'>

<input type="hidden" id="MedikamentID" name="MedikamentID" class="fixed-width4" />

</div>

<script>
 $('#MedikamentID').select2({
                    placeholder: "[Medikament]",
                    allowClear: true,
                    minimumInputLength: 2,
                    ajax: {
                        url: "/Medikament/List",
                        dataType: 'json',
                        data: function (term, page) {

                            return {
                                query: term
                            };
                        },
                        results: function (data, page) {

                            return { results: data };
                        }
                    }
                });

</script>

Whenever you change things using .html() or .innerHTML , essentially, the DOM gets reconstructed and all the javascript events and properties attached to them is lost. 每当您使用.html().innerHTML更改时,从本质.innerHTML ,DOM都会被重建,并且所有附加到它们的javascript事件和属性都将丢失。 But the fix is simple. 但是解决方法很简单。 Just call Select 2 again after you finished inserting the new HTML. 完成插入新HTML后,只需再次调用Select 2。 So something like: 所以像这样:

$.ajax("example.php").done(function(data){
   $("#simpleDiv").html(data)
   $("#MedikamentID").select2(...) //rebuild select2
})

I attached a jsfiddle to illustrate this: http://jsfiddle.net/HT3rP/1/ 我附加了一个jsfiddle来说明这一点: http : //jsfiddle.net/HT3rP/1/

If I got your question correct, you may be having a similar problem related to this stackoverflow problem 如果我的问题正确无误,则可能是与此Stackoverflow问题相关的类似问题

You could try something like this 你可以尝试这样的事情

$(document).on("ready", "#MedikamentID", function () {
    $(this).select2({
       // options go here
    });
});

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

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