我有一个用Backbone.js创建并插入div元素的视图 - 它显示大约一秒然后消失。
以下是我的视图代码:
var addPlayerView = Backbone.View.extend({
tagName: "div",
model: Player,
id: 'addPlayerDiv',
initialize: function() {
console.log('addPlayerView has been created');
},
render: function (){
this.$el.html('<p>show this puppy</p>');
return this;
}
});
这是模型:
var Player = Backbone.Model.extend({
defaults: {
ID: "",
firstName: '',
lastName: ''
},
idAttribute: "ID"
});
这是HTML:
<form onsubmit="addNewPlayer();">
<input type="submit" value="Add New Player New"/>
</form>
<p>
<div id="addPlayerDiv"></div>
</p>
<script>
function addNewPlayer() {
var player = new Player({});
var newPlayerView = new addPlayerView({el: $("#addPlayerDiv"), model: player});
newPlayerView.render();
};
</script>
正在正确调用addNewPlayer()函数并且newPlayerView正在页面上呈现,但只有一秒钟,然后它在页面上消失。
不知道该怎么做。以前有人有这个问题吗?
答案 0 :(得分:3)
您需要取消默认操作(在我们的情况下onsubmit
尝试将数据发送到服务器)
<form onsubmit="addNewPlayer(); return false;">
或
<form onsubmit="addNewPlayer(event);">
function addNewPlayer(e) {
e.preventDefault();
.....
}