[英]Passing as argument to Function Javascript
我有下面的 HTML 表單,Javascript 用於驗證 HTML 表單,因此在文本字段下方有一個隱藏的 P 元素,以顯示其上方的字段中是否有任何錯誤,(fn 文本字段) 上設置了一個 keyup 事件) 根據名稱 (ID = fn) 字段中的輸入觸發和隱藏 P (ID = fnp) 元素此代碼工作正常,但我希望它是動態的,這樣我就不必一次又一次地編寫相同的代碼對於每個文本字段,我想調用 norml 函數並將參數傳遞給 norml 函數(元素名稱),以便它可以對每個文本字段執行相同的操作,但此方法不起作用:任何人都想指導我什么我在這里做錯了。
這是我想做但不起作用的事情:
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>
謝謝..
除其他問題外,主要問題是您在.onkeyup
屬性中設置調用norml(dx, dxx)
的(未定義)結果,而不是傳遞函數引用:
dx.onkeyup = function() {
norml(dx, dxx);
}
其他問題包括:
.onXXX
而不是 DOM3 addEventListener
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.