我正在使用 Backbonejs 框架。在此框架下,我创建了一个app.js,它使用Backbonejs、requirejs、underscore和text.js 我想将 html 页面加载到 div 上。控制台显示 html 页面已加载,但我无法在屏幕上看到该特定页面。
下面是app.js
define(function (require) {
// "use strict";
var $ = require('jquery'),
underscore = require('assets/js/underscore'),
Backbone = require('assets/js/backbone'),
tpl = require('text!Views/home.html'),
template = _.template(tpl);
return Backbone.View.extend({
render: function () {
el: '#banner',
this.$el.html(template());
return this;
}
});
});
我想将 home.html 加载到主屏幕(index.html)。我在index.html 中调用了这个app.js。控制台显示以下 XHR 已完成加载: GET "file:///D:/Project1/Views/home.html" 但我的index.html页面没有显示这个home.html
最佳答案
代码存在许多问题。
- 需要实例化主干 View
- el 需要在渲染函数之外定义
- 需要手动或从初始化函数(在创建 View 实例时调用)调用渲染函数
- 整体结构写得不好,但我不会纠正它,因为它超出了这个问题的范围。
检查这个 fiddle :http://jsfiddle.net/rahulsv/c4dveax9/
var tpl = "<div>hello world</div>";
var template = _.template(tpl);
(function(){
var View = Backbone.View.extend({
el: '#banner',
initialize: function(){
this.render();
},
render: function () {
this.$el.html(template());
}
});
var v = new View();
})();
希望有帮助。
更新:
要使用 requireJs 从文件访问模板(因为您正在使用它),您可以执行以下操作:
模板文件:
<!-- pod.html -->
<h2><%= title %></h2>
<p><%= body %></p>
从 JS 访问模板:
// view.js
define(["text!templates/pod.html"], function(pod) {
var View = Backbone.View.extend({
template: _.template(pod)
});
});
查看此链接以供引用:http://kilon.org/blog/2012/11/3-tips-for-writing-better-backbone-views/
关于javascript - html 页面的渲染不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26334191/