这是我用来进行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);
答案 0 :(得分: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);