1:在平时的开发过程中,难免会遇到<select><input>下拉框,我们有时候需要在选定下拉内容的同时希望触发事件,在这里有两个选择。如:
<select id="ddlApkType" name="ddlApkType" class="select2-selection__rendered" style="width: 114px; height: 29px;" onChange="getCategory()">
<option value="0">全部</option>
<option value="1">游戏</option>
<option value="2">应用</option>
</select>
1):添加onclick="function()",function()表示我们前端所定义的方法,但是这种方法的弊端是在你还没有选定好的情况下就自行直接触发,用户体验极度不佳。
2):第二种方式则是如上所示,添加一个onChange="function()"属性,这种情况下的用户体验较为理想。
2:而在现在的开发过程中,我们更多习惯采取ajax进行局部刷新,因此,在前端定义一个方法:
function getCategory()
{
var appType = $("#ddlApkType").val();
$.ajax({
type: "Post",
url: '/AppMarket/AppMarket_AppList/GetTreeCodes?appType=' + appType,
cache: false,
async: false,
dataType: "json",
success: function (data) {
for (var i = 0; i < data.length ; i++) {
var li = '<option>' + data[i].text + '</option>';
$("#ddlApkCategory").append("<option>" + data[i].text + "</option>");
}
}
})
}:
备注:清除原有<select>中的<option>的方法:$("#ddlApkCategory").find("option").remove();
3:这种情况就是利用ajax进行获取数据,后台数据的获取方式为:
[HttpPost]
[HandlerAjaxOnly]
public ActionResult GetTreeCodes(ApkMainCategory appType)
{
List<TCategory> list = SelectLogic.FindCategoryByType(appType);
var treeList = new List<TreeSelectModel>();
foreach (TCategory item in list)
{
TreeSelectModel treeModel = new TreeSelectModel();
treeModel.text = item.name;
treeList.Add(treeModel);
}
return Content(treeList.ToJson());
}
其中,实体类TreeSelectModel为:
public class TreeSelectModel
{
public string id { get; set; }
public string text { get; set; }
public string parentId { get; set; }
public object data { get; set; }
}
4:何惧真理无穷,进一寸有一寸的欢喜,共勉!