Javascript 对 <!-- ko if: $parent.name == name --> 在淘汰赛 js 中感到困惑

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14589493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:18:15  来源:igfitidea点击:

Confused about <!-- ko if: $parent.name == name --> in knockout js

javascriptknockout.js

提问by blue-sky

I've encountered this Knockout code and I'm confused about what the below code is performing:

我遇到了这个 Knockout 代码,我对下面的代码正在执行的操作感到困惑:

   <!-- ko if: $parent.name == name -->
   <a data-bind='text: name'></a> 
   <!-- /ko -->

Shouldn't this code be interpreted as a comment?

这段代码不应该被解释为注释吗?

Reading the documentation:
http://knockoutjs.com/documentation/custom-bindings-for-virtual-elements.html
this looks like a custom binding?

阅读文档:
http: //knockoutjs.com/documentation/custom-bindings-for-virtual-elements.html
这看起来像一个自定义绑定?

回答by War10ck

It's a knockout conditional comment. The HTML inside the comment block is only executed if the code validates to true. Knockout can read and process this comment for you. You don't have to do anything special. Simply supply the conditional and make sure the variables you reference do in fact exist. Then sit back and let knockout do the rest.

这是一个淘汰条件评论。注释块中的 HTML 仅在代码验证为 true 时才执行。Knockout 可以为您读取和处理此评论。你不必做任何特别的事情。只需提供条件并确保您引用的变量确实存在。然后坐下来,让淘汰赛完成剩下的工作。

回答by Juan Campa

It's not a custom binding. What you encountered is what knockout's documentationcalls a "Virtual Element", it's a binding applied to a piece of code instead of an element. If you want to conditionally evaluate (i.e. bind to your viewmodel) a part of the DOM you can either put it inside a div with an ifbinding or put it inside comments like those.

这不是自定义绑定。您遇到的是淘汰赛文档中所谓的“虚拟元素”,它是应用于一段代码而不是元素的绑定。如果您想有条件地评估(即绑定到您的视图模型)DOM 的一部分,您可以将它放在带有if绑定的 div 中,或者将其放在类似的注释中。

HTML comments are part of the DOM so there's nothing stopping knockout from retrieving and interpreting them.

HTML 注释是 DOM 的一部分,因此没有什么可以阻止淘汰赛检索和解释它们。