javascript - 如何使用 jQuery 部分更新 DOM

标签 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() 进行更新。

最佳答案

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

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

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

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;
}

关于javascript - 如何使用 jQuery 部分更新 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43922581/

相关文章:

javascript - 脚本在 jQuery 中不起作用

javascript - 如何在不使用 jquery append 的情况下插入元标记?

javascript - 无法从 XML 数据完全填充 HTML 表

javascript - 如何实现滚动条

javascript - jQuery - 获取 Alt 文本并添加到警报

javascript - 主干集合获取不会更新@collection.length

javascript - jQuery 溢出 : Hidden on Parent, 检测 child 是否实际上可见

javascript - Wordpress 联系表单中的 Ajax 帖子

javascript - 下划线模板显示对象数组通过_.each

javascript - 如何更改 jquery easyPiechart 的百分比值