问题描述
我使用任务生成了几行< tr>
。现在,通过单击 span
,可以将每个任务标记为完成。我用ajax请求这样做。
I generate several rows <tr>
with tasks. Now, each task can be marked as complete by clicking on a span
. I do that with an ajax request.
这是html:
<table>
<tr>
<td>#1</td>
<td><span class="icon-complete-a to-heal"></span></td>
</tr>
<tr>
<td>#2</td>
<td><span class="icon-complete-a to-heal"></span></td>
</tr>
<tr>
<td>#3</td>
<td><span class="icon-complete-a to-heam"></span></td>
</tr>
</table>
现在当我点击某个span元素时,只有那个元素应该改变类。
Now when I click on a certain span element, only that element should change class.
我用它来改变类:
$(".to-heal").addClass("completed-task");
但我所有的span元素都是完成的课程。
But all my span elements are getting the completed class.
所以我尝试了以下内容:
So I tried with the following:
$(this).find(".to-heal").addClass("completed-task");
但这不起作用。
任何帮助?
更新
我尝试使用 $(this).addClass(completed-task);
这是我正在使用的完整ajax请求:
Here is the full ajax request I'm using:
$(".to-heal").click(function() {
var task = $(this).attr("data-task");
$.ajax({
type: "post",
url: "assets/js/ajax/mark-as-complete.php",
data: { 'task': task },
success: function() {
$(this).addClass("completed-task");
$(".completed-task").click(function() {
var task = $(this).attr("data-task");
$.ajax({
type: "post",
url: "assets/js/ajax/mark-as-incomplete.php",
data: { 'task': task },
success: function() {
$(this).removeClass("completed-task");
}
});
});
}
});
});
标记类不再相同了,因为我使用虚拟类来快速解释。对不起...
The markup classes are not the same anymore, as I used dummy classes for quick explanation. Sorry for that...
非常感谢
推荐答案
背景在ajax调用中丢失了元素。您可以在ajax中使用 context
选项来设置任何元素上下文:
The context of element is lost in ajax call. you can use context
option in ajax to set any elements context:
context:this,
Ajax call snippet:
Ajax call snippet:
$.ajax({
type: "post",
context:this,
url: "assets/js/ajax/mark-as-incomplete.php",
data: { 'task': task },
success: function() {
$(this).removeClass("completed-task");
}
});
这篇关于jquery为这个被点击的元素添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!