我调用一个将表格注入页面的服务:
$('.lobSelect').click(function (e) {
e.stopPropagation();
var yOffset = $(this).position().top + $(this).height() + 'px';
var xOffset = $(this).position().left + 'px';
$('<div class="dropdown-wrapper"></div>')
.css('top', yOffset)
.css('left', xOffset)
.html('foo')
.prependTo('body');
$.ajax({
url: 'http://localhost:15485/api/lineofbusiness',
type: 'get',
dataType: 'json'
})
.done(function (data) {
var table = '<table class="multi-column-table">'
data.forEach(function (item) {
table += '<tr>';
table += '<td data-target-class="lobSelect">' + item.LOB_Code + '</td>';
table += '<td data-target-class="">' + item.LOB_Name + '</td>';
table += '</tr>';
});
$('.dropdown-wrapper').html(table);
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
});
为什么这会附加一个处理程序:
$('body').on('click', '.multi-column-table tr', function () {
//do stuff
});
但不是这个:
$('.multi-column-table tr').on('click', function () {
//do stuff
});
编辑
我曾认为 On() 允许您将处理程序绑定到将来注入的元素。有没有更好的方法可以在不使用 $('body') 的情况下做我正在尝试的事情?