我有一个这样的模板:
<script id="notesTemplate" type="text/html">
<li class="Note">
<div class="NoteDate" data-bind="style: { backgroundColor: background, color: color}">
<span data-bind="text: date"></span>
</div>
<div class="NoteRight" data-bind="style: { backgroundColor: background, color: color}">
<div class="NoteContent">
<span data-bind="text: content"></span>
</div>
<div class="line" data-bind="style: { borderColor: color}"></div>
<div class="NoteCategory" data-bind="style: { color: color}">
<span data-bind="text: category"></span>
</div>
</div>
</li>
</script>
如您所见,我创建了一个带有注释的简单列表(我设置了一些 css 样式,因为每个注释项都有自己的背景和颜色,但是,这是正确的方法吗?)但是:
我想设置 NoteDate
div 的高度等于 NoteRight
div。我实际上是在 JS 中这样做的:
$(function () {
ko.applyBindings(new viewModel());
$(".Note").each(function (index, element) {
var date = $(element).find(".NoteDate");
var note = $(element).find(".NoteRight");
date.height(note.height());
});
});
但这有点慢,因为笔记是使用 Ajax 检索的,我必须使用 async: false
进行调用,否则在“each”运行之前不会获取笔记。
所以:可以将该代码“翻译”成模板吗?我试过类似的东西:
<div class="NoteDate"
data-bind="style: { backgroundColor: background,
color: color, height: $('.NoteRight').height() }">
但这行不通。
经过更多的尝试,我现在有了这个函数(afterRender
):
this.updateNotesLayout = function (elements) {
var date = $(elements).find(".NoteDate");
var note = $(elements).find(".NoteRight");
alert(date.height());
alert(note.height());
date.height(note.height());
alert(date.height());
}
但是日期和笔记高度是 0,但是在旧示例中,两种情况下的高度都是正确的。
有什么想法吗?
最佳答案
针对模板呈现的元素运行代码的最简单选择是使用模板绑定(bind)的 afterRender
回调。
http://knockoutjs.com/documentation/template-binding.html#note_4_using_the__option
这将允许您在新节点上运行代码。在 foreach 情况下,它针对每个元素运行。
关于jquery - 访问 knockoutjs 模板中 html 标签的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6911871/