【问题标题】:JQuery Select2 not initializeJQuery Select2 未初始化
【发布时间】:2017-02-28 10:40:59
【问题描述】:

我对 jQuery select2 有一个很大的误解

我将 select2 添加到我的下拉列表中:

$('#PartnerAdresse_IdCountry').select2(); 
//#PartnerAddresse_IdCountry is filled with all countries

这是我创建 ASP MVC5 的下拉列表:

@Html.DropDownListFor(model => model.PartnerAdresse.IdCountry, ViewBag.Country as IEnumerable<SelectListItem>, "", new { @class = "form-control", style = "width:100%;" })

// Viewbag 是来自控制器的所有国家/地区的填充

但在我的页面上,什么都没有出现,这是我的控制台中生成的代码:

<select class="form-control" data-val="true" data-val-number="Le champ Pays doit être un nombre." 
id="PartnerAdresse_IdCountry" name="PartnerAdresse.IdCountry" style="width:100%;">
    <option value=""></option>
    <option value="1">Afghanistan</option>
    <option value="2">Afrique du Sud</option>
    <option value="3">Albanie</option>
.
.
.
</select>

我也检查过:

  • 页面中没有双重 id
  • 使用 select2 可以正确生成其他表单

我只有在这个领域有问题...有人可以帮助我吗?


编辑 我已经更改,在我的代码中,使用 select2 更正了: $('#PartnerAdresse_IdCountry').select2();

但问题是一样的

【问题讨论】:

  • 只需将$('#PartnerAdresse_IdCountry').select(); 更改为$('#PartnerAdresse_IdCountry').select2();
  • 是的,对不起,我弄错了,在我的代码中是:.select2()
  • 我不确定选择名称中的. 点是有效标记。如果用下划线替换点会发生什么(使名称与 id 相同)
  • 从所有其他下拉列表中,select2 更改模型名称 (PartnerAdresse.idCountry) 并将 . (点)到一个下划线,以通过 Id 与 jQuery 一起使用
  • 不要在 jquery 选择器中使用“生成的代码”。 使用本机 ID。 Select2 将隐藏您的选择并在其上创建一个新选择。它不会改变你的身份证或名字!!!

标签: javascript jquery html select select2


【解决方案1】:

函数是select2() 而不是select()。试试下面:

$('#PartnerAdresse_IdCountry').select2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://select2.github.io/select2/select2-3.5.1/select2.css" rel="stylesheet"/>
<script src="https://select2.github.io/select2/select2-3.5.1/select2.js"></script>

<select class="form-control" data-val="true" data-val-number="Le champ Pays doit être un nombre." 
id="PartnerAdresse_IdCountry" name="PartnerAdresse.IdCountry" style="width:100%;"><option value=""></option>
<option value="1">Afghanistan</option>
<option value="2">Afrique du Sud</option>
<option value="3">Albanie</option>
</select>

【讨论】:

    【解决方案2】:

    你应该使用select2() 方法,而不是`select()。

    只需将$('#PartnerAdresse_IdCountry').select(); 更改为$('#PartnerAdresse_IdCountry').select2(); 即可!

    【讨论】:

    • 对不起,这是一个错误......我现在编辑了我的代码有 select2() 实现......这是写这篇文章的错误......对不起
    【解决方案3】:

    最后,经过这么多的搜索,问题出在我这边。

    我的页面是一个具有 5 个独立表单 (Ajax.BeginForm) 的模态视图,在另一种表单中,我使用了具有相同值 (PartnerAdress.IdCountry) 的隐藏表单,在注释该行之后,它终于工作了......

    抱歉,感谢您的回答:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      相关资源
      最近更新 更多