代码如下,注释的也比较清楚。
<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 这样弄不规范的,可能出现莫名的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/76490.html