简体   繁体   English

为什么 jQuery 插件会阻止我的自定义 function 工作?

[英]Why does a jQuery plugin stop my custom function from working?

I want to have my dropdown menus (HTML select) searchable and also based on the value selected from the dropdown I want to enter some text in a textarea.我想让我的下拉菜单(HTML 选择)可搜索,并且还基于从下拉菜单中选择的值,我想在 textarea 中输入一些文本。

The javascript code that adds text to textarea based on the selected value is simple and works.基于所选值将文本添加到 textarea 的 javascript 代码简单且有效。

window.onload=function(){
    var el = document.getElementById('myselect1');
    if(el){
        document.getElementById('myselect1').addEventListener("change", function(e) {
            var value = document.getElementById('myselect1').value;
            if (value.includes('Germany')) {
                document.getElementById("mytextarea1").value = 'Text1\nText2';
            } else {
                document.getElementById("mytextarea1").value = '';
            };              
        });
    };
};

But as soon as I added the Jquery plugin (Select2) that handles the searchable functionality for the dropdown, the javascript code from above stoped working.但是,一旦我添加了处理下拉列表的可搜索功能的 Jquery 插件 (Select2),上面的 javascript 代码就停止了工作。

<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>  
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" /> 

<script type="text/javascript">
    $(document).ready(function() {
        $('.js-example-basic-single').select2();
    }); 

</script>

In this fiddle the javascript that adds text to textarea based on the selected value works: Fiddle1在这个小提琴中,根据所选值将文本添加到 textarea 的 javascript 有效: Fiddle1

In this fiddle the searchable works: Fiddle2在这个小提琴中,可搜索的作品: Fiddle2

Is there any way to avoid this conflict?有什么办法可以避免这种冲突吗? And have both parts of code work?并且代码的两个部分都可以工作吗?

Solution as pointed out by @CBroe was to use the Select2 events as described here . @CBroe 指出的解决方案是使用此处描述的 Select2 事件。

Code that solved the problem:解决问题的代码:

<script type="text/javascript">
    $.noConflict();
    jQuery(document).ready(function($) {
    $(function() {
        $('.js-example-basic-single').select2();
        });
        $('#myselect1').on('select2:select', function (e) {
            var value = document.getElementById('myselect1').value;
            if (value.includes('Germany')) {
                document.getElementById("mytextarea1").value = 'Text1\nText2';
            } else {
                document.getElementById("mytextarea1").value = '';
            };  
        });
    }); 

</script>

Fiddle小提琴

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

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