jQuery Ajax调用:在非闭包中访问引用元素
这是我用来进行ajax调用的代码 我想知道是否有办法访问目标元素。声明的元素目标不起作用,可能是因为我在click的事件处理程序之外定义了函数处理程序 如何访问目标jQuery Ajax调用:在非闭包中访问引用元素,jquery,ajax,Jquery,Ajax,这是我用来进行ajax调用的代码 我想知道是否有办法访问目标元素。声明的元素目标不起作用,可能是因为我在click的事件处理程序之外定义了函数处理程序 如何访问目标 function handleFavorite(data) { if (data.status) { var notification = noty({ text: "Successfully added to favorite", type: "success
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);
我认为解决这个问题的方法是将变量作为参数传递
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);
对不起,我在想别的事。这就是我最终使用的方法。我想知道是否有更干净的方法来传递这个。