简体   繁体   中英

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. 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. You can't use <span/> because span is not one of the void elements . (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; when KO sets the span's contents, it wipes out everything the browser guessed was inside the span.

If you close the span correctly, it works:

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

Live example | source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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