我有以下功能删除一行。我希望通过传入#search_result
来重用此功能。
function row_delete_ajax(event) {
event.preventDefault();
if (confirm(gettext('Are you sure you want to delete this row?'))) {
var url = $(this).attr("href") + "/";
$.post(url, function(result){
$('#search_result').empty();
$('#search_result').append(result);
});
}
};
这是我最初绑定函数的方式,但有点困扰如何将#search_result
传递给row_delete_ajax
$(document).ready(function (){
$('#search_result').find(".row_delete_ajax").click(row_delete_ajax);
}
答案 0 :(得分:3)
另一种方法是使用[eventData]参数:
eventData:将传递给事件处理程序的数据映射。
$(document).ready(function (){
// Create an object with all the properties you want.
var data = { id: '#search_result' };
// Pass the data object as the first parameter in the click-event.
$('#search_result').find(".row_delete_ajax").click(data, row_delete_ajax);
});
然后像这样使用它:
function row_delete_ajax(event) {
event.preventDefault();
if (confirm(gettext('Are you sure you want to delete this row?'))) {
var url = $(this).attr("href") + "/";
$.post(url, function(result){
$(event.data.id).empty();
$(event.data.id).append(result);
});
}
};
另请查看event.data例如。
答案 1 :(得分:2)
您是否考虑过使用data()http://api.jquery.com/jQuery.data/?
存储元信息$(document).ready(function (){
$('#search_result').find(".row_delete_ajax")
.data('target', 'search_result')
.click(row_delete_ajax);
}
然后你的row_delete_ajax看起来如下:
function row_delete_ajax(event) {
event.preventDefault();
if (confirm(gettext('Are you sure you want to delete this row?'))) {
var url = $(this).attr("href") + "/";
var target = $(this).data('target');
$('#' + target).load(url);
}
}
答案 2 :(得分:2)
你必须稍微改写你的点击是这样的:
$(document).ready(function (){
$('#search_result').find(".row_delete_ajax").click(function (event) {
row_delete_ajax(event, $("#search_result"));
});
}
然后更改您的函数以获取两个参数:
function row_delete_ajax(event, searchResult) {
event.preventDefault();
if (confirm(gettext('Are you sure you want to delete this row?'))) {
var url = $(this).attr("href") + "/";
$.post(url, function(result){
searchResult.empty();
searchResult.append(result);
});
}
};