在MVC3中,我有一个 View _Foo:
我有一个 AJAX 成功回调,我在其中渲染一个 html 表格。该部分有效。
因为表是在 ajax.success 内部创建的,所以我必须使用 live
来监听表行上的事件。
我这样做:
$("#FooTable tbody tr").live('click',
function(evt) { checkOrUnCheckCheckbox(evt, $(this)); });
checkOrUnCheckCheckbox
回调设置所选行最后一列中的复选框。
问题来了:但是当再次加载对话框时,live
被绑定(bind)到表。所以现在我有两次相同的绑定(bind),并且每次都会设置和取消设置该复选框。同样,如果我再次打开对话框,它会调用三次,并且它“有效”,但我仍然不希望函数 checkOrUnCheckCheckbox
被多次调用。
解决方案是首先询问它是否已绑定(bind),然后不再使用 live 或其他方式再次绑定(bind)它?
编辑:共享更多代码,以便更好地理解。
// document.ready and the binding
$(document).ready(function () {
initializeDefaults();
// use live to bind table, because the table is created in a ajax callback.
$("#ModtagereTable tbody tr").live('click',
function(evt) { checkMedtag(evt, $(this)); });
});
});
// init. Load of tabel
function initializeDefaults() {
loadModtagerGruppe();
};
//ajax call to get the list and populate the table with it in the ajax callback
function loadModtagerGruppe() {
$.ajax({
url: '/Foo/GetModtagerListe/',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
})
.success(function (result) {
if (result && result.error) {
//Display error message
return;
}
if (result != null) {
var tbody = "";
for (var i = 0; i < result.length; i++) {
var item = result[i];
tbody = tbody + '<tr class="modtagerRow"><td>' +
item.FirmaNavn + '</td>' +
'<td>' + item.Telefon + '</td>';
// Checkbox
tbody = tbody + '<td><input type="checkbox"></td>'
+ '</tr>';
}
$('#ModtagereTable tbody').html(tbody);
}
})
.error(function (xhr, status) {
//Remove spinner
$('#ModtagereTable tbody').html("");
});
}
}
最佳答案
不要使用live
,它已被弃用。将 on
与委托(delegate)事件处理程序一起使用,如下所示:
$('#FooTable').on('click', 'tr', checkOrUnCheckCheckbox);
function checkOrUnCheckCheckbox(event) {
var el = this;
// your check/uncheck logic...
}
请注意,您需要将 jQuery 升级到至少版本 1.7,但您应该已经使用它作为最低版本
关于javascript - 我只需要使用 JQuery 的 Live 绑定(bind)到我的元素一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22067372/