jquery-editable-select在ASP.NET DropDownList中无法生效的问题咨询
解决ASP.NET DropDownList无法使用jquery-editable-select的问题
问题根源是ASP.NET服务器控件会自动生成带前缀的客户端ID,直接用你设置的cmb_year作为jQuery选择器会找不到元素,导致插件初始化失败。以下是两种可行的解决方法:
方法1:强制客户端ID与服务器ID一致
给DropDownList添加ClientIDMode="Static"属性,让ASP.NET生成的客户端ID和你定义的服务器ID完全相同:
<link href="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet"> <asp:DropDownList id="cmb_year" runat="server" ClientIDMode="Static"></asp:DropDownList> <script src="//code.jquery.com/jquery-1.12.4.min.js"></script> <script src="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script> <script> $('#cmb_year').editableSelect(); </script>
方法2:动态获取客户端ID
如果你的页面使用了母版页或用户控件,无法使用Static模式(避免ID冲突),可以通过ASP.NET的ClientID属性获取控件真实的客户端ID:
<link href="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet"> <asp:DropDownList id="cmb_year" runat="server"></asp:DropDownList> <script src="//code.jquery.com/jquery-1.12.4.min.js"></script> <script src="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script> <script> $('#<%= cmb_year.ClientID %>').editableSelect(); </script>
额外注意事项
- 确保脚本在DOM完全加载后执行,建议把初始化代码放在
$(document).ready()中,避免控件未渲染就执行:
$(document).ready(function() { $('#<%= cmb_year.ClientID %>').editableSelect(); });
- 确认后台绑定数据的代码
service.BindDropdownList(cmb_year, "tbl_year", "year", "Id", "order by Id desc");正常执行,下拉框已经正确生成了<option>元素。
内容的提问来源于stack exchange,提问作者s.k.Soni
相关产品推荐
相关产品推荐

