这是我的脚本:
<div id ="success-message">
</div>
<script>
$('form.subscribe').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data ={};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type:method,
data: data,
success: function(response){
$('#success-message').html(response)
}
});
return false;
});
setTimeout(function() {
$('#success-message').fadeOut('slow');
}, 2000); // <-- time in milliseconds
</script>
我有一个 ajax 函数,它会根据您在表单上的输入内容提供错误消息或成功消息。
我收到的消息来自这个 php 脚本:
<?php
header("Refresh:7; url=contact.php");
$email = $_POST['subscribefield'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Dit emailadres klopt niet";
die();
}
$to = "flash1996mph@hotmail.com";
$subject = "Abonee voor de nieuwsbrief";
$body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";
mail($to, $subject, $body);
echo "U heeft zich zojuist aangemeld voor de vandenberg nieuwsbrief";
?>
我现在从名为 success-message 的 div 中的 php 文件输出 2 个 echo,到目前为止一切顺利。但我想让消息在一段时间后消失,所以我添加了这个功能:
setTimeout(function() {
$('#success-message').fadeOut('slow');
}, 2000); // <-- time in milliseconds
但现在它只在出现错误时向我显示消息,例如,现在它仅在表单填写不正确时向我显示消息。当它正确填充时,我什么也得不到。
最佳答案
将响应写入 div 后,如果您已隐藏该 div,请确保再次显示该 div。
类似于:
$('#success-message').html(response).show();
关于javascript - 淡入淡出效果影响我的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724662/