【发布时间】:2012-08-09 19:24:04
【问题描述】:
我需要将id 属性分配给元素,然后触发一个函数,女巫将使用这个独特的id。
HTML:
<div class="item-timeleft" data-bind="id: 'timer'+ID, init: zxcCountDown('timer'+ID, 'message', 20)">
</div>
Javascript:
var data = [];
var viewModel = {
item: ko.observableArray(data)
};
ko.applyBindings(viewModel);
$.ajax({
url: 'api/item/all',
dataType: 'json',
success: function (data) {
var item_array = [];
$.each(data, function (index, item) {
item_array[index] = item;
});
viewModel.item(item_array);
console.log(data);
}
});
其他 javascript 和自定义绑定:
ko.bindingHandlers.id = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).attr('id', valueAccessor());
}
};
function zxcCountDown(id, mess, secs, mins, hrs, days) {
var obj = document.getElementById(id);
alert(obj.id);
var oop = obj.oop;
if (!oop) obj.oop = new zxcCountDownOOP(obj, mess, secs, mins, hrs, days);
else {
clearTimeout(oop.to);
oop.mess = mess;
oop.mhd = [mins, hrs, days];
oop.srt = new Date().getTime();
oop.fin = new Date().getTime() + ((days || 0) * 86400) + ((hrs || 0) * 3600) + ((mins || 0) * 60) + ((secs || 0));
oop.end = ((oop.fin - oop.srt));
oop.to = null;
oop.cng();
}
}
当我在控制台中重新触发该功能时,它工作得很好,但不知何故,我无法弄清楚如何分配 id,然后才触发该功能。
【问题讨论】:
-
我没有时间测试这是否能解决您的整个问题,但对于初学者,您需要在两个绑定表达式中为 ID 添加括号,即:id: 'timer' + ID( )
标签: javascript html data-binding knockout.js