目前我有几个文本输入,然后是一个类型图像提交按钮。在提交按钮上我有onmouseover,onmouseout等。这将它们发送到一个javascript函数,处理悬停效果的图像更改。我想做的是提交表单,然后做一些检查,如密码匹配等。我是否会使用form标签的action属性将其提交给javascript函数?
答案 0 :(得分:1)
首先,我建议使用像jQuery这样的东西。它使代码更容易管理。以下是你在jQuery中的表现:
$('form').submit(function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
以下是您在纯javascript中的表现方式:
// function to make sure we add the event correctly no matter which browser
function addEvent(evnt, elem, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
} else { // No much to do
elem[evnt] = func;
}
}
// get first form on page
var form = document.forms[0];
addEvent('submit', form, function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
答案 1 :(得分:0)
<form onsubmit="return cancel()"><input type="submit" /></form>
<script>
function cancel()
{
//code validation
var validated = false;
if(!validated)return false;
else return true;
}
</script>