我为表行创建了一个 View ,我想监听该行中任何单元格的任何单击。 这就是我的实现方式:
let ListItem = Backbone.View.extend({
events: {
'click tr': 'showDetails',
'click': 'showDetails'
},
template: function() {
return "<tr><td><img src=<%= imageUrl %> /></td><td class='name'><%= firstName %></td><td><%= lastName %></td><td><%= homeTown %></td><td><button type='button' id='ddd' class='btn btn-danger'>Delete</button></td></tr>";
},
render: function() {
var oTemplate = _.template(this.template());
this.$el.html(oTemplate(this.model.toJSON()));
$('table > tbody:last-child').append(this.$el.html());
return this;
},
showDetails: function() {
alert("*****");
},
hide: function(bToHide, index) {
index++;
if (!bToHide) {
$($('tr')[index]).show();
return;
}
$($('tr')[index]).hide();
this.rendered = true;
},
openActorView: function() {
window.open('/#actor/' + window.actorsCollection.indexOf(this.model), '_self');
}
});
单击其中的行\单元格后,没有任何反应。 我听到点击此 View +点击 tr,但没有任何反应。
此外,当向 tr td
添加事件时,以太坊什么也没有发生。
感谢您的帮助
最佳答案
它不起作用的原因
$('table > tbody:last-child').append(this.$el.html());
jQuery .html()
function returns a string 。
因此,您正在创建一个漂亮的 Backbone View ,并且易于定义事件监听器,然后您不使用它,只需获取其字符串表示形式并将其转储到 DOM 中,丢失之前绑定(bind)的任何事件监听器.
改进
首先,不需要将模板做成函数,直接使用_.template
即可。我写了另一个答案,提供了有关 how to use _.template
的更多信息。 .
之后,不要在 View 内使用全局选择器。它会破坏作用域组件 View 的用途。让父 View 类处理这个问题。
let ListItem = Backbone.View.extend({
tagName: 'tr', // the list item is a `<tr>`
events: {
'click': 'showDetails'
},
template: _.template("<td><img src=<%= imageUrl %> /></td><td class='name'><%= firstName %></td><td><%= lastName %></td><td><%= homeTown %></td><td><button type='button' id='ddd' class='btn btn-danger'>Delete</button></td>"),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
showDetails: function() {
console.log("show details event");
}
});
创建一个管理表的 ListView 。这是将列表项放入 DOM 的父类。
不要使用 jQuery 核心函数,而是使用 Backbone view scoped alias this.$()
缓存表体。
let ListView = Backbone.View.extend({
initialize: function() {
this.$body = this.$('tbody');
},
render: function() {
this.$body.empty();
this.collection.each(this.renderItem, this);
return this;
},
renderItem: function(model) {
var view = new ListItem({ model: model });
this.$body.append(view.render().el); // use the DOMElement
}
});
然后从 View 外部传递一个现有表。
new ListView({ el: 'table.my-table' }).render();
<小时/>
这是一个 super 基本的示例,您应该意识到性能可以进一步提高,并且如果按原样使用它可能会泄漏内存。
关于javascript - 主干事件点击表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44522538/