Bind JSON object to HTML element

前端 未结 6 661
自闭症患者
自闭症患者 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:51

    First, add id attributes to your markup (you could do this with the DOM but for clarity's sake ids are probably best suited for this example):

    John
    Smith

    Use a jQuery event handler to update the fields whenever they are modified (this is an inefficient solution but gets the job done- worry about optimizing once you have something functional):

    // declare your object
    function person(firstn, lastn) {
        this.firstname = firstn;
        this.lastname = lastn;
    }
    
    var myGuy = new person("John", "Smith");
    
    $(document).ready(function () {
        $("#firstname").change(function () {
            myGuy.firstname = $("#firstname").val();
        });
    
        $("#lastname").change(function () {
            myGuy.lastname = $("#lastname").val();
        });
    
        // etc...
    });
    

    Now every time the fields are updated your object will be too.

提交回复
热议问题