简体   繁体   English

Select2() 不是 function

[英]Select2() is not a function

So i have downloaded select2 i have "installed it" by putting it into my folder and then loaded it on my site when i check the console (where i can see all of the scripts being loaded) i can see the file select2.js所以我已经下载了 select2 我已经通过将它放入我的文件夹来“安装它”,然后在我检查控制台时将它加载到我的网站上(在那里我可以看到所有正在加载的脚本)我可以看到文件 select2.js

I went to their documentation and copied it and added $("#e9").select2();我去了他们的文档并复制了它并添加了$("#e9").select2();

However when i load the page i get the following error:但是,当我加载页面时,出现以下错误:

TypeError: $(...).select2 is not a function


$("#e9").select2();

Have anyone else experianced anything like this?有没有其他人经历过这样的事情?

Additional information here is my script:这里的附加信息是我的脚本:

    jQuery(document).ready(function(){
    var max_amount = parseFloat($('#max_amount').val());
    $( "#item_amount" ).keyup(function() {
           if($(this).val() > max_amount){
            $(this).val( max_amount);
        }
        if( /\D/.test($(this).val()) ){
            alert('Må kun indeholde tal!');
            $(this).val('');
        }
        if($(this).val()== '0'){
            alert('Må ikke være 0!');
            $(this).val('');
        }
    });
    $("#e1").select2();

});
function addToBasket(){
    var amount = $('#item_amount').val();
    if(amount == ""){
        amount = 1;
    }

    if(amount > 0){
    $.ajax({
        type: 'POST',
        url: myBaseUrl + 'Products/addItemToBasket',
        dataType: 'json',
        data: {
            id: window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1),
            amount: amount
        },
        success: function (data) {
            var urlToBasket = myBaseUrl+'Products/basket';
            var newAmount = parseInt(amount)
            var price = data[0]['Product']['pris'];
            var id = data[0]['Product']['id'];
            var dat = data;
            var tmp_basket_html = $('#basket_amount').html();
           if($('#basket_amount').html() !== " Tom"){
              $('#shopping_table_body').append(
                  "<tr id='"+id+"'>" +
                      "<td class='image'>" +
                      ""+
                      "</td>" +
                      "<td class='name'>" +
                      " "+data[0]['Product']['name'] +
                      "</td>"+
                      "<td class='quantity'>" +
                      "x "+amount +""+
                      "</td>"+
                      "<td class='total'>" +
                      ""+price*amount+
                      "</td>" +
                      ""+
                      "<td class='remove'>" +
                      "<input class='icon-remove' type='button' onclick='removeItemFromBasket("+id+")'>"+
                      "</td>"+
                      "</tr>"
              );
           }else{
               $("#shopping_menu").append(
                   "<ul class='dropdown-menu topcartopen'>"+
                       "<li id='basket_list'>"+
                      "<table id='shopping_table'>"+
                        "<tbody id='shopping_table_body'>"+
                       "<tr id='"+id+"'>" +
                       "<td class='image'>" +
                       ""+
                       "</td>" +
                       "<td class='name'>" +
                       " "+data[0]['Product']['name'] +
                       "</td>"+
                       "<td class='quantity'>" +
                       "x "+amount +""+
                       "</td>"+
                       "<td class='total'>" +
                       ""+price*amount+
                       "</td>" +
                       ""+
                       "<td class='remove'>" +
                       "<input class='icon-remove' type='button' onclick='removeItemFromBasket("+id+")'>"+
                       "</td>"+
                       "</tr>"+
                       "</table>"+
                       "</li>"+
                       "<div class='well pull-right'>"+
                       "<input type='button' onclick='goToBasket()' class='btn btn-success' value='Tjek ud'>"+
                       "</div>"+
                       "</ul>"

               )
           }
            updateTotal(amount,price);
            updateBasketAmount();
        }
    });
    }
    Notifier.success('Vare tilføjet', 'Tilføjet'); // text and title are both optional.
}
function updateTotal(amount, price){
    var price = parseFloat(price);
    var oldValue = parseFloat($('#basket_total_cost').html());
    var newPrice = amount*price+oldValue;
    $('#basket_total_cost').html(newPrice);
}
function updateBasketAmount(){
   var tmp =  $('#basket_amount').html();
    if(!isNaN(tmp)){
   var oldAmount = parseInt(tmp.substr(0,2));
    var i = oldAmount + 1;;
    $('#basket_amount').html(
        ""+i+" vare(r)"
    );
    }else{
        $('#basket_amount').html(
            "1"+" vare(r)"
        );
    }
}
function goToBasket(){
    window.location.href = myBaseUrl+'Products/basket';
}

I was having this problem when I started using select2 with XCrud.当我开始将 select2 与 XCrud 一起使用时,我遇到了这个问题。 I solved it by disabling XCrud from loading JQuery, it was it a second time, and loading it below the body tag.我通过禁用 XCrud 加载 JQuery 来解决它,这是第二次,并将其加载到 body 标记下方。 So make sure JQuery isn't getting loaded twice on your page.因此,请确保 JQuery 不会在您的页面上加载两次。

This error raises if your js files where you have bounded the select2 with select box is loading before select2 js files.如果在 select2 js 文件之前加载使用选择框绑定 select2 的 js 文件,则会引发此错误。 Please make sure files should be in this order like..请确保文件应按此顺序排列,例如..

  • Jquery查询
  • select2 js选择 2 js
  • your js你的js

Had the same issue.有同样的问题。 Sorted it by defer loading select2通过延迟加载 select2 对其进行排序

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js" defer></script>

I was also facing same issue & notice that this error occurred because the selector on which I am using select2 did not exist or was not loaded.我也遇到了同样的问题,请注意,发生此错误是因为我使用 select2 的选择器不存在或未加载。

So make sure that $("#selector") exists by doing因此,通过执行以下操作确保 $("#selector") 存在

if ($("#selector").length > 0)
   $("#selector").select2();

document.ready()函数中添加$("#id").select2()

I used the jQuery slim version and got this error.我使用了 jQuery slim 版本并收到此错误。 By using the normal jQuery version the issue got resolved.通过使用普通的 jQuery 版本,问题得到了解决。

The issue is quite old, but I'll put some small note as I spent couple of hours today investigating pretty same issue.这个问题已经很老了,但我会写一些小笔记,因为我今天花了几个小时调查同样的问题。 After I loaded a part of code dynamically select2 couldn't work out on a new selectboxes with an error "$(...).select2 is not a function".在我动态加载部分代码后,select2 无法在新的选择框上运行,并显示错误“$(...).select2 不是函数”。

I found that in non-packed select2.js there is a line preventing it to reprocess the main function (in my 3.5.4 version it is in line 45):我发现在非打包的 select2.js 中有一行阻止它重新处理 main 函数(在我的 3.5.4 版本中它在第 45 行):

 if (window.Select2 !== undefined) { return; }

So I just commented it out there and started to use select2.js (instead of minified version).所以我只是在那里评论它并开始使用 select2.js (而不是缩小版本)。

 //if (window.Select2 !== undefined) { // return; //}

And it started to work just fine, of course it now can do the processing several times loosing the performance, but I need it anyhow.它开始工作得很好,当然它现在可以进行多次处理而失去性能,但无论如何我都需要它。

Hope this helps, Vladimir希望这会有所帮助,弗拉基米尔

config.assets.debug = false放在 config/environments/development.rb 中。

您可能指的是出现上述错误的两个 jquery 脚本。

For me, select2.min.js file worked instead of select2.full.min.js .对我来说, select2.min.js文件工作而不是select2.full.min.js I have manually define files which I have copied from dist folder that I got from github page .我已经手动定义了从github page获得的 dist 文件夹中复制的文件。 Also make sure that you have one jQuery(document).ready(...) definition and jquery file imported before select2 file.还要确保在 select2 文件之前导入了一个jQuery(document).ready(...)定义和 jquery 文件。

For newbies like me, who end up on this question: This error also happens if you attempt to call .select2() on an element retrieved using pure javascript and not using jQuery.对于像我这样的新手,最终会遇到这个问题:如果您尝试对使用纯 javascript 而不是使用 jQuery 检索的元素调用 .select2() ,也会发生此错误。

This fails with the "select2 is not a function" error:这因“select2 不是函数”错误而失败:

document.getElementById('e9').select2();

This works:这有效:

$("#e9").select2();

In my case, I was getting this error in my rails app when both webpacker and sprockets were trying to import jQuery.就我而言,当 webpacker 和 sprockets 都尝试导入 jQuery 时,我在 Rails 应用程序中收到此错误。 I didn't notice it until my code editor automatically tried to import jQuery into a webpacker module.直到我的代码编辑器自动尝试将 jQuery 导入 webpacker 模块时,我才注意到它。

I was having the same problem today and none of the other answers worked.我今天遇到了同样的问题,其他答案都没有奏效。 I don't understand how or why this worked, but it did and (knock on wood) still does.我不明白这是如何或为什么起作用的,但它确实并且(敲木头)仍然有效。

But first, a bit about my specific situation:但首先,关于我的具体情况:

I was using select2 in one .js file and trying to get it into another one, but got this error.我在一个 .js 文件中使用 select2 并尝试将其放入另一个文件中,但出现此错误。 jQuery was working fine in the other .js document, and the second one I tried to use was called LATER in the html than the first .js document I was writing, and both later than the jquery and select2 tags. jQuery 在另一个 .js 文档中运行良好,而我尝试使用的第二个在 html 中比我正在编写的第一个 .js 文档更晚,并且都晚于 jquery 和 select2 标签。

OK, now for the solution that doesn't make sense, but does work:好的,现在对于没有意义但确实有效的解决方案:

I put the definition of the jQuery element into the earlier .js file and the .select2 on that variable in the later .js file.我将 jQuery 元素的定义放入较早的 .js 文件中,并将该变量的 .select2 放入较晚的 .js 文件中。 Weird, right?很奇怪吧? So, like this:所以,像这样:

<head>
*blah blah blah html headers*
<script src="/static/js/jquery-3.6.0.js"></script>  
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body>
*blah blah blah page stuff*
<script src="/static/js/first.js"></script>
*blah blah some more stuff*
<script src="/static/js/second.js"></script>

first.js第一个.js

const selector = $('#select-this')

second.js第二个.js

selector.select2({
*&c, &c, &c.*

ControlId.select2({...}); ControlId.select2({...}); was not working but following worked:没有工作,但以下工作:

$(ControlId).select2({...}); $(ControlId).select2({...});

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

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