gpt4 book ai didi

javascript - 每次按下按钮时清除 View 并重新开始 - backbone.js

转载 作者:行者123 更新时间:2023-11-30 18:09:11 24 4
gpt4 key购买 nike

每次我按下按钮时,它都会添加我的数据并重新加载页面,然后列表就会消失。 preventdefault 起作用了,但每次我单击该按钮时,它都会不断添加到列表中。

如何清除列表并在每次单击按钮时重新开始?

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
<script type="text/javascript" src="Scripts/underscore.js"></script>
<script type="text/javascript" src="Scripts/backbone.js"></script>

</head>
<body>

<div>

<div id="container">
<button>Load</button>
<ul id="list"></ul>
</div>

<div id="list-template">
<li><a href=""></a></li>
</div>


<script type="text/javascript" src="JavaScript.js"></script>


</div>

</body>
</html>

JavaScript

model = new Backbone.Model({

data: [

{ text: "site 1", href: "link1.htm" },
{ text: "site 2", href: "link2.htm" },
{ text: "site 3", href: "link3.htm" },
{ text: "site 4", href: "link4.htm" },
{ text: "site 4", href: "link4.htm" },
{ text: "site 4", href: "link4.htm" },
{ text: "site 4", href: "link4.htm" },

]
});

var View = Backbone.View.extend({

initialize: function () {
//console.log('initializing ' + this.options.blankOption);
this.template = $('#list-template').children();
},
el: '#container',
events: {
'click button' : 'render'
},
//model:model,
render: function(event){
//event.preventDefault();
var data = this.model.get('data');
for (var i = 0; i < data.length; i++) {
var li = this.template.clone().find('a').attr('href', data[i].href).text(data[i].text).end();
this.$el.find('ul').append(li);
}



}
});

最佳答案

原因是每次单击按钮时,整个 View 都会再次呈现并附加到现有内容。这将解决您的问题:

// empty the content inside the $el and re-rendering.
this.$el.empty();
this.$el.find('ul').append(li);

关于javascript - 每次按下按钮时清除 View 并重新开始 - backbone.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15064364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com