作为参数传递给函数Javascript

时间:2016-04-30 22:41:54

标签: javascript html keyup

我有以下HTML表单,Javascript用于验证HTML表单,因此在文本字段下方有一个隐藏的P元素,以显示其上方字段中是否有任何错误,有一个关键字事件设置在(fn textfield)根据名称(ID = fn)字段中的输入触发和隐藏P(ID = fnp)元素,此代码工作正常,但我希望它是动态的,这样我就不必编写相同的代码对于每个文本字段,我想一次又一次地调用norml函数并将参数传递给norml函数(元素名称),以便它可以对每个文本字段执行相同的操作,但是此方法不起作用:ANYBODY将会像引导我,我在这里做错了什么。

这就是我想要做的事情:

document.getElementById("fn").onkeyup = norml(pass an element name);

function norml(value received)
document.getelementbyID(received element ID name).color = red;

实施例

function norml(dx, dxx)  // receives a value as argument that is an element ID
{
    dx.style.borderColor = '#d6d6d6';
    dx.style.color = '#000000';
    dxx.style.innerHTML = '';
    dxx.style.visibility = 'hidden';    
}

这是什么工作但是必须为每个文本领域单独进行

function norml()
{
    document.getElementById("fn").style.borderColor = '#FF0000';
    document.getElementById("fn").style.color = '#FF0000';
    document.getElementById("fnp").style.borderColor = '#FF0000';
    document.getElementById("fnp").style.innerHTML = '';
    document.getElementById("fnp").style.visibility = 'hidden'; 
}

function validate() {
    var errmsg = "";
    var result = true;

    var fname = document.getElementById("fn").value;
    if (!fname.match(/^[a-zA-Z]+$/))
        {
            document.getElementById("fn").style.borderColor = '#FF0000';
            document.getElementById("fn").style.color = '#FF0000';
            document.getElementById("fnp").style.backgroundColor = 'lightpink';
            document.getElementById("fnp").style.visibility = 'visible';
            document.getElementById("fnp").innerHTML = "Please enter first name in alphabets";
            document.getElementById("fn").onkeyup = norml;
            return false;
        }
    if (errmsg != ""){   //only display message box if there is something to show
    alert(errmsg);
}
}

function init()
{
    var formData = document.getElementById("enqForm");
    formData.onsubmit = validate;
}

window.onload = init;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts.js"></script> 
<title></title> 
</head>
<body id="enquire">
<section id="form">
    <div>
    <form id="enqForm" method="post">
        <div class="formobj">
            <div id="enquiry"><h1></h1></div>
                <input id="fn" type="text" name="firstname" placeholder="First Name *" />
                <input id="ln" type="text" name="lastname" placeholder="Last Name *" />
                <p id="fnp" type="hidden"></p>
                <p id="lnp" type="hidden"></p>
                    <input id="sendbutton" type="submit" value="Enquire" />
        </div>
    </form>
    </div>
</section>
</body>
</html>

感谢..

1 个答案:

答案 0 :(得分:1)

在其他问题中,主要问题是您在norml(dx, dxx)属性中设置调用.onkeyup的(未定义)结果,而不是传递函数引用:

dx.onkeyup = function() {
    norml(dx, dxx);
}

其他问题包括:

  • 反复调用以反复获取相同的元素
  • 然后重复调用deference元素的样式对象
  • 使用DOM0 .onXXX代替DOM3 addEventListener