select2 不是函数

select2 is not a function

我有这个html

 <div class="input-box">
        <select id="billing:country_id" class="validate-select" name="billing[country_id]" title="Country">
            <option value=""> </option>
        </select>
    </div>
    <div class="input-box">
        <select id="billing:region_id" class="validate-select" name="billing[region_id]" title="State">
            <option value=""> </option>
        </select>
    </div>

<script type="text/javascript">
    jQuery("#billing\:country_id").select2({
        placeholder: "Select a Country"
    });

    jQuery("#billing\:region_id").select2({
        placeholder: "Select State"
    });

    jQuery("#billing\:country_id").change(function(){
        jQuery("#billing\:region_id").select2('destroy'); 

        jQuery("#billing\:region_id").select2({
            placeholder: "Select a State"
        });
    });
</script>

但是当我尝试更改国家/地区下拉列表时出现此错误:

TypeError: jQuery(...).select2 不是函数

jQuery("#billing\:region_id").select2('destroy');

我没有看到任何错误,只是你的整个函数应该封装在里面 jquery.To 演示,我只是添加了 3 个选项。

$(function(){
    $("#billing\:country_id").select2({
        placeholder: "Select a Country"
    });

    $("#billing\:region_id").select2({
        placeholder: "Select State"
    });

    $("#billing\:country_id").change(function(){
        $("#billing\:region_id").select2('destroy'); 

        $("#billing\:region_id").select2({
            placeholder: "Select a State"
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>

<div class="input-box">
    <select id="billing:country_id" class="validate-select" name="billing[country_id]" title="Country">
        <option value=""> </option>
  
  <option value="1">option 1 </option>
  <option value="2">option 2 </option>
  <option value="3">option 3 </option>
    </select>
</div>
<div class="input-box">
    <select id="billing:region_id" class="validate-select" name="billing[region_id]" title="State">
        <option value=""> </option>
  <option value="1">option 1 </option>
  <option value="2">option 2</option>
  <option value="3">option 3</option>
    </select>
</div>

这里是 JsFiddle Link.