Why last name does not show in Knockout js sample

2019-07-21 03:22发布

问题:

I am knock out newbie and have the sample code like the following

<p>First Name: <strong data-bind="text: firstName" /></p>
 <p>Last Name: <strong data-bind="text: lastName" /></p>

 <script type="text/javascript">
 function AppViewModel() {
     this.firstName = "First";
     this.lastName = "Last";
 }
 ko.applyBindings(new AppViewModel());

When I run the code all I see is

FirstName: First First

I do not see the lastname and also the first name repeated twice. I am using ASP.Net empty project to create a html file as the default page. I am using 2.0.0 version of knock out. Thanks.

回答1:

I'd try

<p><strong data-bind="text: lastName"></strong></p>

Added I just tried the above in the knockout tutorial and it worked.

Whereas

<p><strong data-bind="text: lastName"/></p>

did not work and broke knockout effects after the <strong/> element. (On windows chrome browser.)

Why the problem I think the <strong> element was not originally created in the dom because it was a self-closed element. Then knockout came along and tried to add html content to it. Result: the html was displayed, but in a way that interfered with the subsequent knockout dom changes.

In any case: test on multiple browsers and don't use self-closing elements when they aren't normally expected. Eg <strong/>