你好我做了一个代码,需要在ajax调用后添加一个类。我确信代码是正确的,但仍然没有添加类。它真的很奇怪,因为代码中的其他一切都有效,我确信addClass的代码是正确的,我也检查过控制台是否存在任何错误,但没有错误。这是我的代码
$(document).on('click', '.miclickks', function(event) {
event.preventDefault();
var for_uid = $(this).parents("li").attr('data');
var for_name = $(this).parents("li").attr('unme');
var for_pic = $(this).parents("li").attr('upic');
var owner_uid = $('.row-fluid').attr('uid');
var owner_name = $('.row-fluid').attr('usnm');
var owner_pic = $('.row-fluid').attr('usp');
var type = "kiss";
var dataString = "type=" + type + "&for_uid=" + for_uid + "&for_name=" + for_name + "&for_pic=" + for_pic + "&owner_uid=" + owner_uid + "&owner_pic=" + owner_pic + "&owner_name=" + owner_name;
$.ajax({
type: "POST",
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300")
{
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else
{
$(this).addClass('active');
}
}
});
});
答案 0 :(得分:6)
两种方式:
的第一强> :
var that = this;
$.ajax({
type: "POST",
url: "include/ajax.php",
data: dataString,
success: function (html) {
if (html == "300") {
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
} else {
$(that).addClass('active');
}
}
});
第二次 (使用context
选项):
$.ajax({
type: "POST",
url: "include/ajax.php",
data: dataString,
context: this,
success: function (html) {
if (html == "300") {
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
} else {
$(this).addClass('active');
}
}
});
答案 1 :(得分:2)
试试这个 -
var $p = $(this);
$.ajax({
type: "POST",
url: "include/ajax.php",
data: dataString,
success: function (html) {
if (html == "300") {
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
} else {
$p.addClass('active');
}
}
});
答案 2 :(得分:1)
原因是this
内的success()
是XHR对象而不是被点击的元素。您可以使用context
选项将其强制为您想要的任何值。
例如:
$.ajax({
context: this, // pass the clicked element via context
...
success: function() {
...
$(this).addClass('active'); // now this refers to the clicked element
}
});
答案 3 :(得分:0)
也许我说错了,有人会纠正,但我认为错误出现在这条指令中:$(this).addClass('active');
在这种情况下,“this”指的是ajax对象,所以请确保你正在调用proprer对象,在该对象上添加活动类