0

这是我用来进行 ajax 调用的代码

我想知道是否有办法访问目标元素。声明的元素目标不起作用可能是因为我在事件处理程序之外定义函数处理程序以进行点击

如何访问目标

function handleFavorite(data) {
    if (data.status) {
        var notification = noty({
            text: "Successfully added to favorite",
            type: "success"
        });
    } else {
        var notification = noty({
            text: data.error,
            type: "error"
        });

    }
    target.toggleClass("btn-danger").toggleClass("add").toggleClass("delete");
}

function toggleFavorite() {
    var href = $(this).attr("href");
    var target = $(this);

    $.get(href, handleFavorite, "json");
    return false;
}

$(".favorite").click(toggleFavorite);   

在对此进行了更多思考之后,我认为这将是最好的解决方法:通过接受元素作为参数的函数返回处理函数:

function createHandler($element){
    var target=$element;
    return function(data){
        if (data.status) {
          var notification = noty({
             text: "Successfully added to favorite",
             type: "success"
         });
         } else {
            var notification = noty({
            text: data.error,
            type: "error"
          });

     } 
    target.toggleClass("btn-danger").toggleClass("add").toggleClass("delete");
 }

}
//And in the ajax call
function toggleFavorite() {
    var href = $(this).attr("href");
    var target = $(this);

    $.get(href, createHandler($(this)), "json");
    return false;
}

$(".favorite").click(toggleFavorite);   
4

1 回答 1

2

我认为解决它的方法是将变量作为参数传递

function handleFavorite(target, data) {
    if (data.status) {
        var notification = noty({
            text: "Successfully added to favorite",
            type: "success"
        });
    } else {
        var notification = noty({
            text: data.error,
            type: "error"
        });

    }
    target.toggleClass("btn-danger").toggleClass("add").toggleClass("delete");
}

function toggleFavorite() {
    var href = $(this).attr("href");
    var target = $(this);

    $.get(href, function(){
        handleFavorite(target, data)
    }, "json");
    return false;
}

$(".favorite").click(toggleFavorite);   
于 2013-07-10T10:45:16.600 回答