我希望有人可以帮助我的项目学校。我有一段这样的 HTML 代码:
<!DOCTYPE html>
<html>
<head>
<title>Tambah Guru</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type='text/javascript' src='script.js' charset="utf-8"></script>
</head>
<body>
Email: <input type='text' id='txtemail' />
<input type='submit' value='Simpan' id='validateemail' />
</body>
</html>
然后我的 Javascript 代码是:
$(document).ready(function(e) {
$('#validateemail').click(function() {
var sEmail = $('#txtemail').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
if (validateEmail(sEmail)) {
alert('Email is valid');
} else {
alert('Invalid Email Address');
e.preventDefault();
}
});
});
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
} else {
return false;
}
}
当我运行它时,它不起作用。我不知道为什么。有人可以帮我吗?
最佳答案
您没有像上面的评论中那样添加 jQuery。将此行放在 html 中的脚本行上方
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
然后您就不会传入要处理的事件对象。在点击处理程序中传递事件对象,如下面的代码所示。您正在 document.ready 中传递事件处理程序,但这不是您需要的。
$(document).ready(function() {
$('#validateemail').click(function(e) {
var sEmail = $('#txtemail').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
if (validateEmail(sEmail)) {
alert('Email is valid');
}
else {
alert('Invalid Email Address');
e.preventDefault();
}
});
});
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
关于javascript - 我的 Javascript 无法在 localhost XAMPP 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16631659/