【发布时间】:2014-07-09 00:01:50
【问题描述】:
我在 html 中有元素,它具有 css 的数据绑定。 后面的字段是 ko.computed。
在计算函数中,我需要访问元素的id。
如何在 ko.computed 函数中获取元素?
代码示例:
<span id="ship" style="cursor:pointer" data-bind="click:changeItem, css:computeActive" >ship</span>
<span id="cat" style="cursor:pointer" data-bind="click:changeItam, css:computeActive" >cat</span>
<span id="dog" style="cursor:pointer" data-bind="click:changeItem, css:computeActive" >dog</span>
查看模型:
var vm = {
computeActive: function () {
return data.selectedItem()== (****here is the place where I want to use object id****)?
"activeText":"inActiveText" ;
},
changeItem: function (event, sender) {
data.selectedItem(sender.currentTarget.id);
}
};
我不想要:
1.使用 knockout.bindingHandler
2。为每个元素编写分离的计算函数
【问题讨论】:
-
你能发布一些代码吗?为什么在计算中需要元素 id?这通常是一种反模式,您需要在视图模型中使用此类信息,因此可能有一种更淘汰的方式来执行此操作...
-
我已经添加了一个例子
-
如果没有正确的解释为什么你不想要某些东西它与你不想要的东西并不真正相关。 ;-)