移动事件处理程序以分隔文档

时间:2013-01-15 02:41:40

标签: javascript html

我目前正在使用此HTML代码:

<form onsubmit="return validateForm()" action="page.html" >
Name:  <input type="text" id="name" /><br />
Email: <input type="text" id="email" /><br />
<input type="submit" value="Submit" />
</form> 

但是我想将我的事件处理程序移动到我的单独的javascript中,进入名为initiate的函数。我的javascript看起来像这样:

function formValidator(){

    var name = document.getElementById("name");
    var email = document.getElementById("email");


    if(isAlphabet(name, "Fill in name"))
    {

        if(emailValidator(email, "Fill in email"))
        {
            return true;
        }
    }


    return false;

}

function isAlphabet(elem, helpMsg)
{
    var alphaExp = /^[a-zA-Z]+$/;
    if(elem.value.match(alphaExp))
    {
        return true;
    }
    else
    {
        alert(helpMsg);
        elem.focus();
        return false;
    }
}

function emailValidator(elem, helpMsg)
{
    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    if(elem.value.match(emailExp))
    {
        return true;
    }
    else
    {
        alert(helpMsg);
        elem.focus();
        return false;
    }
}


function initiate {
    // ..
}
window.onload = initiate;

到目前为止,我只是想出了如何编写代码来重定向到新网页,但它没有检查它是否是一个有效的代码。我用过这个:

HTML

<form id="form">
Name:  <input type="text" id="name" /><br />
Email: <input type="text" id="email" /><br />
<input type="submit" value="Submit" />
</form>

的Javascript

document.getElementById("form").action = "page.html";

但我无法弄清楚如何编写,以便.action="page.html"return validateForm()都有效。

1 个答案:

答案 0 :(得分:1)

您的表单需要id

<form id="form">
Name:  <input type="text" id="name" /><br />
Email: <input type="text" id="email" /><br />
<input type="submit" value="Submit" />
</form> 

单独的Javascript文件:

function initiate()
{
    var form = document.getElementById("form");
    form.action = "page.html";
    form.onsubmit = function validateForm()
    {
        var name = document.getElementById("name");
        var email = document.getElementById("email");


        if(isAlphabet(name, "Fill in name"))
        {

            if(emailValidator(email, "Fill in email"))
            {
                return true;
            }
        }

        return false;
    };
}

window.onload = initiate;

如果某些内容未验证,请确保validateForm()函数返回false。