2

我有以下功能来删除一行。我想通过传入#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_resultrow_delete_ajax

$(document).ready(function (){  
    $('#search_result').find(".row_delete_ajax").click(row_delete_ajax);
}
4

3 回答 3

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例如。

于 2012-11-21T21:23:21.920 回答
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);
    }
}
于 2012-11-21T21:12:37.687 回答
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);
        });                
    }       
};
于 2012-11-21T21:13:33.743 回答