gre*_*row 3 ajax jquery jquery-animate
可能重复:
加载Ajax内容后滚动到顶部
我有一个ajax表单,提交时会显示错误或成功消息,理想情况下,我想将浏览器滚动到表单顶部,以便用户可以看到这些消息,但是当我实现此功能时,它似乎无法正常工作而且我不知道如何解决它:-/它滚动得不够高或刷新吗?:(我很茫然,如果你能指导我的话,那太好了:)
$('#submit').bind('click', function(){
$('body, html').animate({scrollTop:$('form').offset().top}, 'slow', 'easeInCubic');
$.ajax({
url:$(this).attr('action'),
type:'POST',
data:$('form').serialize(),
dataType:'json',
success:function(respond) {
if(respond.result == 'false') {
var error_msg = '<h3>Please correct the following errors:</h3><ul>'+respond.errors+'</ul>';
$('.error_msg').html(error_msg);
} else {
var success_msg = '<h3>Success!</h3>';
$('.error_msg').empty();
$('.success_msg').html(success_msg);
$('form').find("input[type=text], textarea").val("");
setTimeout(function() {
$('.success_msg').slideUp();
}, 5000);
}
}
});
return false;
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<form method="post" action="form.php">
<div class="error_msg"></div>
<div class="success_msg"></div>
<label for="name">Name?</label>
<input type="text" value="" name="name" />
<label for="email">Email?</label>
<input type="text" value="" name="email" />
<input id="submit" type="submit" value="Submit" name="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
实际上我会以两种方式做到这一点:
第一:
$(function(){
function submitForm(){
$.ajax({
url:"a.php",
type:"post",
success:function(data){
alert(data);
},
complete:function(){
$('body, html').animate({scrollTop:$('form').offset().top}, 'slow');
}
});
}
$('#submit').click(function(){
submitForm();
});
});
Run Code Online (Sandbox Code Playgroud)
在这里,我创建了一个函数SubmitForm(),然后单击输入类型按钮以提交它。
或使用提交按钮的更好方法:
第二:(我喜欢这种方式)
$(function(){
$('form').submit(function(e){
e.preventDefault();
$.ajax({
url:"a.php",
type:"post",
success:function(data){
alert(data);
},
complete:function(){
$('body, html').animate({scrollTop:$('form').offset().top}, 'slow');
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12962 次 |
最近记录: |