为什么模板div会显示为“:hidden"?在afterRender中? [英] Why are template divs showing as ":hidden" in afterRender?

查看:99
本文介绍了为什么模板div会显示为“:hidden"?在afterRender中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么模板div在afterRender中显示为:hidden"?

Why are template divs showing as ":hidden" in afterRender?

这是代码:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
  <script src="js/jquery.tmpl.js"></script>
  <script src="js/knockout-1.2.1.debug.js"></script>
  <script>
  $(document).ready(function() {
        m = function (name)
        {
          this.name = name;
        }

        viewModel = {
          a : ko.observableArray(),
          sparkie : function (elements) {
            div = elements[0];
            console.log($(div).is(':hidden'));
          },
        }

        ko.applyBindings(viewModel);

        viewModel.a.push(new m('oh-no'));
    });
    </script>
</head>
<body>

<script type="text/html" id="tpl">
  <div> ${ $data.name } </div>
</script>

<div data-bind='template: { name: "tpl", foreach: a, afterRender: sparkie }'></div>

</body>
</html>

推荐答案

afterRender适用于

自定义 DOM上的后处理逻辑 模板生成的元素

custom post-processing logic on the DOM elements generated by your templates

但是不幸的是,它在您的模板准备好后(在DOM上应用)被调用,但是它还没有插入到html中.

BUT unfortunately it is invoked after your template is ready (applied on the DOM), but it's not inserted into the html just yet.

如果您使用的是foreach,则淘汰赛将 调用您的afterRender回调 每一项添加到您的可观察范围 数组

If you’re using foreach, Knockout will invoke your afterRender callback for each item added to your observable array

,但是如果您正在传递模板的数据,则还会被调用一次.

but if will also be invoked once if you are passing the data for the template.

KO允许您添加afterAdd和/或 beforeRemove回调进行操作 添加/删除的DOM元素 自定义方式

KO allows you to give afterAdd and/or beforeRemove callbacks to manipulate the added/removed DOM elements in a custom way

,因此将为observableArray中的每个添加/删除的项目调用这些方法. 当调用它们时,您的DOM已经准备就绪,因此您将不再隐藏它,但是仅在更改基础observableArray时才调用这些回调.

so those will be invoked for every added/removed item in the observableArray. When these are being called your DOM is ready, so you it won't be hidden anymore, but these callbacks are only invoked when the underlying observableArray is changed.

<div data-bind="template: { name: 'tpl', foreach: a, afterAdd: sparkie }"></div>

这篇关于为什么模板div会显示为“:hidden"?在afterRender中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆