需要进行哪些修改才能使以下代码中的所有子div元素向上或向下滑动,而不仅仅是在此处编码的第一个子div元素:
HTML:
<!-- ko fadeIf: show -->
<div data-bind="text: name" style="display: none"></div>
<div data-bind="text: name2" style="display: none"></div>
<!-- /ko -->
<input type="checkbox" data-bind="checked: show" /> Show
JS:
(function() {
var getFirstRealElement = function(element) {
return ko.utils.arrayFirst(ko.virtualElements.childNodes(element) || [], function(el) {
return el.nodeType === 1;
});
};
var makeTemplateValueAccessor = function(valueAccessor) {
return function() { return { 'if': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } };
};
ko.bindingHandlers.fadeIf = {
init: ko.bindingHandlers['if'].init,
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor()),
child = getFirstRealElement(element),
updater = function() {
ko.bindingHandlers.template.update(element, makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
$(getFirstRealElement(element)).slideDown('slow');
};
if (child) {
$(child).slideUp('slow', updater);
} else {
updater();
}
}
};
ko.virtualElements.allowedBindings.fadeIf = true;
})();
var viewModel = {
name: ko.observable("Bob"),
name2: ko.observable("Mary"),
show: ko.observable(false)
};
ko.applyBindings(viewModel);
答案 0 :(得分:0)
您可以通过更改此行来调整updater
方法以选择所有子节点而不仅仅是第一个子节点:
$(getFirstRealElement(element)).slideDown('slow');
为:
$(ko.virtualElements.childNodes(element)).slideDown('slow');
因此,您的updater
方法现在将如下所示:
updater = function() {
ko.bindingHandlers.template.update([...params]);
$(ko.virtualElements.childNodes(element)).slideDown('slow');
};
这是一个工作示例http://jsfiddle.net/JdG5m/1/