Javascript Span addClass不工作ajax
我有这样一个spanJavascript Span addClass不工作ajax,javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,我有这样一个spanjoin event。 我使用这个函数通过AJAX进行点击操作 但是在success函数中,我似乎无法将类添加到单击的跨度中 function accept() { $(".to-join").click(function() { var id = $(this).attr("data-event"); $.ajax({ type: "post", url: "../assets/
join event
。
我使用这个函数通过AJAX进行点击操作
但是在success函数中,我似乎无法将类添加到单击的跨度中
function accept() {
$(".to-join").click(function() {
var id = $(this).attr("data-event");
$.ajax({
type: "post",
url: "../assets/js/ajax/toggle-events.php",
data: { 'id': id },
success: function() {
alert("good job");
$(this).addClass("joined");
},
error: function () {
alert("fail");
}
});
});
}
您需要将$(this)
定义为ajax调用外部的变量,ajax内部的这个变量将引用jqXHR
对象
function accept() {
$(".to-join").click(function() {
var id = $(this).attr("data-event"),
$this=$(this);
$.ajax({
type: "post",
url: "../assets/js/ajax/toggle-events.php",
data: { 'id': id },
success: function() {
alert("good job");
$this.addClass("joined");
},
error: function () {
alert("fail");
}
});
});
}
您需要将$(this)
定义为ajax调用外部的变量,ajax内部的这个变量将引用jqXHR
对象
function accept() {
$(".to-join").click(function() {
var id = $(this).attr("data-event"),
$this=$(this);
$.ajax({
type: "post",
url: "../assets/js/ajax/toggle-events.php",
data: { 'id': id },
success: function() {
alert("good job");
$this.addClass("joined");
},
error: function () {
alert("fail");
}
});
});
}
使用ajax方法的
context
选项:
context: this,
contextType:PlainObject此对象将是所有Ajax相关回调的上下文。默认情况下,上下文是
表示调用中使用的Ajax设置($.ajaxSettings)
将设置传递到$.ajax)
使用ajax方法的
context
选项:
context: this,
contextType:PlainObject此对象将是所有Ajax相关回调的上下文。默认情况下,上下文是
表示调用中使用的Ajax设置($.ajaxSettings)
将设置传递到$.ajax)
成功回调中的
$(this)
不是您期望的$(this)
。我如何获得我期望的$(this)?有解决方案吗?使用.bind
或创建一个类似var$self=$(this)的引用
并在回调中使用$self
,或者将附加选项上下文:this
传递给$。ajax
您必须使用$(“.to join”)
$(this)
再次引用您的元素。成功回调中的$(this)
不是您期望的值。我如何获得我期望的$(this)值?有解决方案吗?使用.bind
或创建一个类似var$self=$(this)的引用
并在回调中使用$self
,或者将additional option上下文传递给$。ajax
您必须使用$(“.to join”)
再次引用元素。这里要注意的关键是this
在ajax调用中不同,因为它在函数中使用,与accept()
不同的函数。这里需要注意的关键是此
在ajax调用中不同,因为它在函数中使用,与accept()
不同。