将JSON对象绑定到HTML元素 [英] Bind JSON object to HTML element
问题描述
我想将JSON对象绑定到HTML元素。
I want to bind a JSON object to a HTML element.
例如
我有一个对象person属性为firstName,lastName
I have a object "person" with the attributes "firstName", "lastName"
<div class="person-list">
<div class="person-list-item">
<div>John</div> ---> bind it to person.firstName
<div>Smith</div> ---> bind it to person.lastName
</div>
</div>
所以,如果HTML元素的值被改变,那么对象的人也会被更新。
so, if a value of the HTML elements gets changed, then will also the object person gets updated.
是否可以以任何方式?
我使用:
- jquery
- ASP.NET MVC 3
推荐答案
如果您在应用程序中执行此操作很多,可能需要引入一个库,例如优秀的 Knockout.js ,它使用MVVM来执行绑定。
If you'll be doing this a lot in your application, you may want to bring in a library such as the excellent Knockout.js which uses MVVM to do bindings as you describe.
你的标记看起来像这样:
Your markup would look something like this:
<div data-bind="text: firstName"></div>
<div data-bind="text: lastName"></div>
在您的JavaScript中:
And in your JavaScript:
function MyViewModel() {
this.firstName = "John";
this.lastName = "Smith";
}
ko.applyBindings(new MyViewModel());
如果有很多人,您还可以使用数据集。如果您想了解如何执行此操作,请尝试本教程:使用列表和集合。
You can also use a data set if there are many "people." Try out this tutorial if you would like to learn how to do that: Working with Lists and Collections.
其他有用的链接
- Introduction tutorial
- Excellent demo video (about 30 minutes)
这篇关于将JSON对象绑定到HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!