Bind JSON object to HTML element

前端 未结 6 672
自闭症患者
自闭症患者 2020-12-31 13:29

I want to bind a JSON object to a HTML element.

e.g.

I have a object \"person\" with the attributes \"firstName\", \"lastName\"

6条回答
  •  忘掉有多难
    2020-12-31 13:38

    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:

    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.

    Other useful links:

    • Introduction tutorial
    • Excellent demo video (about 30 minutes)

提交回复
热议问题