我有一个observableArray
self.workouts = ko.observableArray([
{name: "Chest/Biceps", exercises:self.exercises1},
{name: "Back/Triceps", exercises:self.exercises2},
{name: "Legs/Shoulders", exercises:self.exercises3},
]);
exercises1
看起来像这样:
self.exercises1 = ko.observableArray([
{name: "bench press", sets:self.sets},
{name: "machine chest press", sets:self.sets1},
{name: "standing biceps curl", sets:self.sets2},
{name: "machine biceps curl", sets:self.sets3}
]);
我想要的是为id
中的每个对象添加一个唯一的exercises1
,然后将其绑定到我的视图中。我试过使用attr绑定,但没有成功。
我的观点如下:
<div class="content">
<ul data-bind="foreach: workouts">
<li class="name"><a class="name" data-bind="text:name"></a>
<ul class="hhide" data-bind="foreach: exercises">
<li class="name_ex"><a data-bind="text:name"></a>
<div class="hhide">
<input id ="weight" type="text" placeholder="weight(kg)">
<span id="append">x</span>
<input id ="reps" type="text" placeholder="reps">
<button id="sets" data-bind="click: $root.addSet">Add set</button>
<div data-bind="foreach: sets">
<div id="sets" class="remove" data-bind="click: $root.removeSet">delete</div>
<div data-bind="visible: !editing(), text: name, click: edit"></div>
<input data-bind="visible: editing, value: name, hasFocus: editing" />
</div>
</div>
</li>
</ul>
</ul>
</div>
谢谢!
答案 0 :(得分:1)
这是你在找什么? (小提琴:http://jsfiddle.net/U7EFz/4/)
HTML:
<div class="content">
<ul data-bind="foreach: workouts">
<li class="name"><a class="name" data-bind="text:name"></a>
<ul class="hhide" data-bind="foreach: exercises">
<li class="name_ex">
<a data-bind="text:name, attr:{id:uniqueId}"></a>
| uniqueId:
<span data-bind="text:uniqueId"></span>
</li>
</ul>
</li>
</ul>
</div>
JS:
var VM = function(){
var self = this;
var idCounter = 0;
self.getId = function(){
return "id" + (++idCounter);
}
self.exercises1 = ko.observableArray([
{name: "bench press", uniqueId:"id1"},
{name: "machine chest press", uniqueId:"id2"},
{name: "standing biceps curl", uniqueId:"id3"},
{name: "machine biceps curl", uniqueId:"id4"}
]);
self.workouts = ko.observableArray([
{name: "Chest/Biceps", exercises:self.exercises1},
{name: "Back/Triceps", exercises:self.exercises1},
{name: "Legs/Shoulders", exercises:self.exercises1},
]);
}
ko.applyBindings(new VM())