您的位置:首页 > 其它

记录一次使用knockout实现表格中select绑定,并选中默认值。

2018-03-23 23:33 435 查看
代码如下,注释的也比较清楚。<body>
<div id="maindiv">
<div>
<div>
<table class="table table-striped">
<thead>
<tr>
<th>id</th>
<th>候选</th>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody data-bind="foreach: aList">
<tr>
<th data-bind="text:id"></th>
<th>
<select data-bind="options:aoptionlist, value: a, optionsText: 'Name' ,optionsText='Value'" ></select>
</th>
<th data-bind="click:aSave">保存</th>
<th data-bind="click:aDel">删除</th>
</tr>
</tbody>

</table>
</div>
<button type="button" class="btn btn-info" id="adda" data-bind="click:addafun">新增</button>
</div>
</div>
<script type="text/javascript">

function myViewModel() {
var self = this;

/**
* 一行的数据格式
* @param id
* @param aindex 默认选项在aoptionlist的下标
*/
function aVO(id,aindex){
this.id=id;
this.a=ko.observable(aoptionlist[aindex]); //这种可以绑定默认值
// this.a=ko.observable(aoptionlist);//夏斌啊这俩句一起也可以
// this.a(aoptionlist[aindex]);
console.info("this :");
console.info(this);
}
//展现的所有数据
self.aList = ko.observableArray();
// a 某列的的select中的所有 option 用一个数组
this.aoptionlist =getaOptionList();
this.aSave = function ($data) {
console.info("进入aSave id是"+$data.id);
console.info("进入aSave a");
console.info($data.a);
console.info("进入aSave a.Value");
console.info($data.a().Value);//vo 不加括号是undefined
}

this.aDel = function ($data) {
console.info("进入aDel id是"+$data.id);
console.info("进入aDel a");
console.info($data.a);
console.info("进入aDel vo.Value");
console.info($data.a().Value);//vo 不加括号是undefined
console.info("$data : ");
console.info($data);
self.aList.remove($data);//经过各种实验前边啥也不加就获取到了

}
this.getaList = function () {
}
this.addafun = function () {
var i = Math.ceil(Math.random()*100);
var id = i;
tmp = new aVO(id,i%3);//传入所在数组的索引
this.aList.push(tmp);
}
function getaOptionList() {
//todo 这个是需要后台配置文件里可配的
return [
{ Name: "AA", Value:"11" },
{ Name: "BB", Value: "22" },
{ Name: "CC", Value: "33" }
];
}
getaList();

}

ko.applyBindings(myViewModel(),$("#maindiv")[0]);

</script>
</body>使用踩坑记录 ,要让<select data-bind="options:aoptionlist, value: a, optionsText: 'Name' ,optionsText='Value'" ></select>中的a 要绑定的值是对应的optionsValue的值(目前体现为一个字符串,而不是一个对象),不然可能出现下拉列表无法选中我们想要的被选选项。
还有不要没有ptionsValue 这样弄不规范的,可能出现莫名的问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  knockout 下拉框
相关文章推荐