我有以下AJAX代码正常工作,除了我想在刚检查的输入字段中添加类的部分。
输入字段:
<input type="text" class="solution" id="input_rebus" name="answer" />
AJAX代码:
$('.solution').on("change", function(){
var form_data = {
name: $(this).val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('homework/submit'); ?>",
type:'POST',
data: form_data,
success: function(msg){
$('#message').html(msg);
this.addClass('solution_correct');
//outputs: Correct!
},
error: function(msg){
$('#message').html(msg);
this.addClass('solution_wrong');
//outputs: Wrong! Try again!
}
});
return false;
});
</script>
所以,问题出在“this.addClass('...')行; 我尝试过使用$(this),但这也没用。
这可能是非常愚蠢的事情,但我似乎无法弄明白!
提前致谢:)
答案 0 :(得分:0)
继承人的方式
$('.solution').on("change", function(){
var $self = $(this);
var form_data = {
name: $(this).val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('homework/submit'); ?>",
type:'POST',
data: form_data,
success: function(msg){
$('#message').html(msg);
$self.addClass('solution_correct');
//outputs: Correct!
},
error: function(msg){
$('#message').html(msg);
$self.addClass('solution_wrong');
//outputs: Wrong! Try again!
}
});
return false;
});
答案 1 :(得分:0)
您可以在调用$ .ajax时设置context
属性,该属性将在所有回调中设置为this
。
$('.solution').on("change", function(){
var form_data = {
name: $(this).val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('homework/submit'); ?>",
type:'POST',
context: $(this),//<--- here
data: form_data,
success: function(msg){
$('#message').html(msg);
this.addClass('solution_correct');
//outputs: Correct!
},
error: function(msg){
$('#message').html(msg);
this.addClass('solution_wrong');
//outputs: Wrong! Try again!
}
});
return false;
});
</script>