[英]Javascript: how to bring focus to an element, and show a warning message
序言,我真的根本不懂javascript。
我正在嘗試驗證表單的電子郵件地址。 如果驗證失敗,我想關注無效的電子郵件字段,並顯示警告消息。 如果刪除了“ focusElement”行,則以下代碼正確返回true或false。 但是,它總是在包含該行的情況下返回true(大概是因為該行無效並且代碼無法執行。是否有適當/簡單的方式專注於此元素並顯示消息?
function validateForm(formElement)
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailPattern.test(formElement.tfEmail.value))
{
return true;
}
else
{
focusElement(formElement.tfEmail,'Please enter a valid e-mail address.');
return false;
}
}
...
else
{
alert('Please enter a valid e-mail address.');
formElement.tfEmail.focus();
return false;
}
如果您希望功能與您的示例一樣處於單獨的功能中:
...
else
{
focusElement(formElement.tfEmail, 'Please enter a valid e-mail address.');
return false;
}
function focusElement(obj, msg)
{
alert(msg);
obj.focus();
}
嘗試:
alert("Ur err msg"); document.getElementById("yourEmailFieldId").focus();
function focusElement(el, message) {
alert(message);
el.focus();
}
您應該嘗試使用jQuery和jQuery Validate來完成此任務。
jQuery是最常用的JavaScript框架,它可以簡化JavaScript中的許多任務。
jQuery Validate是基於jQuery的非常有用的驗證插件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.