简体   繁体   English

Knockoutjs:使用相同的viewModel属性绑定多个html元素

[英]Knockoutjs:bind multiple html elements with same viewModel's property

I want to bind single viewModel's property with two html elements but its not working. 我想绑定单个viewModel的属性与两个html元素,但它不起作用。 It's binding the model's property only to the first element.The reason for doing this is that I want to show a form with same data (both edit and read only views of form). 它只是将模型的属性绑定到第一个元素。这样做的原因是我想要显示一个具有相同数据的表单(包括编辑和只读形式的视图)。 Kindly suggest if there is any better approach to solve this problem(to provide edit/readonly view for form easily) . 请建议是否有更好的方法来解决这个问题(轻松提供表单的编辑/只读视图)。

Following is what I wanted to do right now. 以下是我现在想做的事情。

<span data-bind="text: name"/>
<input data-bind="value: name" />

The problem is that your span isn't closed. 问题是你的span没有关闭。 You can't use <span/> because span is not one of the void elements . 您不能使用<span/>因为span不是void元素之一 (Self-closing tags are only for elements that cannot contain anything, like <br/> or <input/> ; you only need the / in them for XHTML, although it's allowed in HTML [it's just meaningless].) So since the span isn't closed, the browser has to guess what you meant the span to contain; (自闭标签只适用于不能包含任何内容的元素,例如<br/><input/> ;你只需要/在它们中用于XHTML,虽然它在HTML中是允许的[它只是毫无意义]。)所以既然span没有关闭,浏览器必须猜测你所指的span是什么; when KO sets the span's contents, it wipes out everything the browser guessed was inside the span. 当KO设置跨度的内容时,它会清除浏览器猜测的跨度内的所有内容。

If you close the span correctly, it works: 如果正确关闭span ,它可以正常工作:

<span data-bind="text: name"></span>
<input data-bind="value: name" />

Live example | 实例 | source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM