我正在使用对象数组来创建一个复选框选择器,但出于某种原因,当我单击一个复选框时它会返回默认值。为什么会这样?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="knockout-2.2.1.js"></script>
<script src="knockout.mapping-latest.js"></script>
</head>
<body>
<span data-bind="text: name"></span>
<ul data-bind="foreach: alldata">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: $data.name"> </span>
<input type="checkbox" data-bind="attr: { value: $data }, click: myFunction.bind($data),checked: $data.rc " />
</li>
</ul>
<hr />
<div data-bind="text: ko.toJSON(viewModel)"></div>
<script type="text/javascript">
var tObj = {"name":"John", "roles":[{id:1, name:"Role1", desc:"Desc1"}, {id:2, name:"Role2", desc:"Desc2"}]};
var lstRoles=[{id:1, name:"Role1", desc:"Desc1", rc:true},{id:2, name:"Role2", desc:"Desc2", rc:false},{id:2, name:"Role3", desc:"Desc3",rc:true},{id:2, name:"Role4", desc:"Desc4", rc:false}];
var viewModel = ko.mapping.fromJS(tObj);
viewModel.alldata = ko.observableArray(lstRoles);
//viewModel.alldata.subscribe();
ko.applyBindings(viewModel);
function myFunction(data)
{
//viewModel.roles.push(data);
}
</script>
</body>
</html>
更新代码: 我已经创建了1部分问题,它与click:myFunction.bind($ data)事件有关,如果删除它开始工作的点击事件。但仅限于tObj.Roles而不是alldata数组。
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="knockout-2.2.1.js"></script>
<script src="knockout.mapping-latest.js"></script>
</head>
<body>
<span data-bind="text: name"></span>
<div data-bind="foreach: alldata">
<input type="checkbox" data-bind="attr: { value: $data }, checked: $data.rc, enable: $data.ds" />
<span data-bind="text: $data.name"> </span>
<span data-bind="text: $data.desc"> </span></br>
</div>
<hr />
<div data-bind="foreach: roles">
<input type="checkbox" data-bind="attr: { value: $data }, checked: $data.rc" />
<span data-bind="text: $data.name"> </span>
<span data-bind="text: $data.desc"> </span></br>
</div>
<hr />
<div data-bind="text: ko.toJSON(viewModel)"></div>
<script type="text/javascript">
var tObj = {"name":"John", "roles":[{id:1, name:"Role1", desc:"Desc1", rc:true, ds:true},{id:2, name:"Role2", desc:"Desc2", rc:false, ds:false},{id:2, name:"Role3", desc:"Desc3",rc:true, ds:false},{id:2, name:"Role4", desc:"Desc4", rc:false, ds:true}]};
var lstRoles=[{id:1, name:"Role1", desc:"Desc1", rc:true, ds:true},{id:2, name:"Role2", desc:"Desc2", rc:false, ds:false},{id:2, name:"Role3", desc:"Desc3",rc:true, ds:false},{id:2, name:"Role4", desc:"Desc4", rc:false, ds:true}];
var viewModel = ko.mapping.fromJS(tObj);
viewModel.alldata = ko.observableArray(lstRoles);
//viewModel.alldata.subscribe();
ko.applyBindings(viewModel);
function myFunction(data)
{
//viewModel.roles.push(data);
}
</script>
</body>
</html>
答案 0 :(得分:1)
合理,它与默认点击操作相关联,即复选框值更改。尝试使用return true;来自点击处理程序。