我确信jQuery工作正常,但由于某种原因它不适合我。我甚至无法将它放入jsFiddle,因为它不喜欢Ajax,但我的$(this).children
语句根本不起作用。我没有收到任何错误......我做错了什么?
JS
$('.submitNewOrder').submit( function() {
$(this).children('input[type=\"submit\"]').prop('disabled',true); // Doesn't work
$(this).children('.saving').fadeIn('fast'); // Doesn't work
$.ajax({
url: 'scripts/submitNewOrder.php?catID=1',
data: newOrder,
type: 'POST',
mode: 'abort',
success: function(){
$(this).children('.saving').fadeOut('fast', function() { // Doesn't work
$(this).children('.success').fadeIn('fast'); // Doesn't work
});
},
error: function(){
$(this).children('.error').fadeIn('fast'); // Doesn't work
}
});
return false;
});
HTML
<form class="submitNewOrder">
<p>
<input type="submit" value="Save order" />
<span class="saving" style="display:none">Saving changes...</span>
<span class="success" style="display:none">Saved!</span>
<span class="error" style="display:none">There was a problem saving :(</span>
</p>
</form>
答案 0 :(得分:6)
尝试将children
替换为find
,如:
$('.submitNewOrder').submit(function () {
var $this = $(this);
$this.find('input[type=\"submit\"]').prop('disabled', true);
$this.find('.saving').fadeIn('fast');
$.ajax({
url: 'scripts/submitNewOrder.php?catID=1',
data: newOrder,
type: 'POST',
mode: 'abort',
success: function () {
$this.find('.saving').fadeOut('fast', function () {
$this.find('.success').fadeIn('fast');
});
},
error: function () {
$this.find('.error').fadeIn('fast');
}
});
return false;
});
答案 1 :(得分:3)
使用ajax的context选项并使用.find()
代替.children()
:
$.ajax({
url: 'scripts/submitNewOrder.php?catID=1',
data: newOrder,
type: 'POST',
mode: 'abort',
context: this, //<< HERE so in callback functions, 'this' refers to the object, not options object of ajax call
success: function(){
$(this).find('.saving').fadeOut('fast', function() {
$(this).find('.success').fadeIn('fast');
});
},
error: function(){
$(this).find('.error').fadeIn('fast');
}
});
答案 2 :(得分:0)
在submit
this
指向form
元素。您要查找的元素不是form
的子元素,而是<p>
的子元素。将您的表达式更改为$(this).find(...)
,这将在树下搜索一个以上的级别。