如何使用jQuery部分更新DOM

时间:2017-05-11 17:59:29

标签: javascript jquery backbone.js backbone-views

我的HTML如下:

<div id="spotPrices">
    <label class="spotLabel">Oil (WTI) $/bbl:</label>
    <INPUT type="text" id="OilSpotPrice" Size=8>
</div>

和我的JavaScript:

ShowSpotPrices = Backbone.Model.extend({
    defaults: {
        wti: "0.00",
    },

    url: function () {
        return 'http://localhost:4000/api/getSpotPrices';
    },

    initialize: function () {
        console.log("Initialized ShowSpotPrices Model...")
    }
});

ShowSpotPricesView = Backbone.View.extend({
   el: '#spotPrices',
   initialize: function() {
        this.listenTo(this.model, 'sync change', this.render);
        this.model.fetch();
        this.render();
   },

    render : function() {
        //this.$("#OilSpotPrice").html("27.45");
        this.$("#OilSpotPrice").html(this.model.get('wti'));
        return this;
    }
});

var spotPrices = new ShowSpotPrices();
spotPrices.fetch({
    success: function (model) {
        console.log("New spotPrices model fetch: " + model.get('wti'));
    },
    failure: function (model) {
        console.log("Failed to fetch spotPrices model");
    }
});

var spotPricesView = new ShowSpotPricesView({model: spotPrices});
console.log("After spotPricesView.render: " + spotPricesView.model.get('wti'));

我可以使用API​​端点成功获取wti值。

但是,我无法使用jQuery更新#OilSpotPrice。我尝试使用固定字符串值进行更新,并使用model.get()

1 个答案:

答案 0 :(得分:1)

使用.val() jQuery function设置#OilSpotPrice输入的,而不是内部HTML。

this.$("#OilSpotPrice").val(this.model.get('wti'));

此外,您可以在find方法中限制为一个jQuery initialize调用。

initialize: function() {
    // cache the jQuery object of the input once
    this.$oilSpotPrice = this.$("#OilSpotPrice");

    this.listenTo(this.model, 'sync change', this.render);
    this.model.fetch();
    this.render();
},

render : function() {
    // then use the object
    this.$oilSpotPrice.val(this.model.get('wti'));
    return this;
}