[英]fadeIn() inside Knockout's afterAdd callback
I am trying to learn the foreach binding and I can't understand why the $(element).fadeIn(500)
line in the code below isn't working: 我正在尝试学习foreach绑定,但我不明白为什么下面的代码中的
$(element).fadeIn(500)
行不起作用:
ko.applyBindings({ myItems: ko.observableArray([ 'A', 'B', 'C' ]), FadeIn: function(element, index, item) { if(element.nodeType == 1){ $(element).fadeIn(500); } }, addItem: function() { this.myItems.push('New item'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <ul data-bind="foreach: { data: myItems, afterAdd: FadeIn }"> <li data-bind="text: $data"></li> </ul> <button data-bind="click: addItem">Add</button>
The problem is that when I add a new item, it appears in the page without the fadeIn effect. 问题是,当我添加新项目时,它出现在页面中而没有fadeIn效果。
Codepen -> https://codepen.io/anon/pen/ejxeBr Codepen-> https://codepen.io/anon/pen/ejxeBr
It's because your element isn't hidden. 这是因为您的元素未隐藏。 Change it to
更改为
$(element).hide().fadeIn(500);
// --------^^^^^^^
...or set style="display: none"
on it in the markup, but that could be a pain because of the pre-existing elements (which won't get afterAdd
calls). ...或在标记中设置
style="display: none"
,但这可能会很afterAdd
,因为已有元素( afterAdd
调用后不会得到)。
Example: 例:
var count = 0; ko.applyBindings({ myItems: ko.observableArray(['A', 'B', 'C']), FadeIn: function(element, index, item) { if (element.nodeType == 1) { $(element).hide().fadeIn(500); } }, addItem: function() { this.myItems.push('New item'); } });
<ul data-bind="foreach: { data: myItems, afterAdd: FadeIn }"> <li data-bind="text: $data"></li> </ul> <button data-bind="click: addItem">Add</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.