如何重用 JavaScript 函数进行表单输入控制

How to reuse JavaScript function for form input control?

本文关键字:表单 输入 控制 何重用 JavaScript 函数      更新时间:2023-09-26

我有一个完全按照我想要的方式工作的输入字段,但是,我有许多字段重复相同的代码。 是否可以调用 JavaScript 函数并获得相同的结果?

这是我目前工作的html:

<input type="text" name="lname" value="Last Name" style="color:gray;" 
onblur="if((this.value == 'Last Name') || (this.value == '')) 
{this.value = 'Last Name'; this.style.color= 'gray';} 
else {this.style.color= 'black';}"
onfocus="if((this.value == 'Last Name') || (this.value == '')) 
{this.value = ''; this.style.color= 'gray';}
else {this.style.color= 'black';}"
onselect="this.style.color= 'black';"
onclick="this.style.color= 'black';"/>

但我希望能够做这样的事情:

<input type="text" name="lname" value="Last Name" style="color:gray;" 
onblur="onBlurAction()";
onfocus....
etc....
</input>
<script>
function onBlurAction()
{
    if((this.value == 'Last Name') || (this.value == '')) 
        {this.value = 'Last Name'; this.style.color= 'gray';} 
    else {this.style.color= 'black';}
}
function onFocusAction....
etc....
</script>

在你的函数中,this引用window全局变量,你应该this作为参数传递:

onblur="onBlurAction(this)"

虽然函数将是这样的:

function onBlurAction(el)
{
    if (el.value == 'Last Name' || el.value == '') {
        el.value = 'Last Name';
        el.style.color = 'gray';
    } else {
        el.style.color = 'black';
    }
}

另一种方法是不更改函数,而是以这种方式使用 onblur

onblur="onBlurAction.call(this)"

可以使用一个函数作为多个事件的处理程序。

<input type="text" name="lname" value="Last Name" style="color:gray;" 
    onblur="onBlurAction();" onfocus="onBlurAction();" .../>

这将需要onBlurAction模糊和对焦事件。您可以为onselectonclick做类似的事情。

你能不使用占位符属性吗?

编辑:

按照托马斯·厄普顿(Thomas Upton)提到的操作是行不通的,因为他使用的是.value属性。一旦用户输入内容,该值就会更改,因此该函数将无法正确检查(默认)值,因为它已被更改。

他可以使用占位符属性来帮助函数。像这样:

        <input type="text" name="lname" value="" placeholder="Last Name" style="color:gray;" 
               onblur="javascript:onBlurAction(this.name);"
               onfocus="javascript:onBlurAction(this.name);"
               onselect="javascript:onBlurAction(this.name);"
               onclick="javascript:onBlurAction(this.name);">
               function onBlurAction(elname)
               {
                   value = document.getElementById(elname).getAttribute("placeholder");
                   if ((this.value == value) || (this.value == ''))
                   {
                       this.value = value;
                       this.style.color = 'gray';
                   }
                   else {
                       this.style.color = 'black';
                   }
               }

他将元素名称传递给函数,此函数将获取占位符值。这将适用于他的所有文本输入,按照他的意愿重用该函数。在这里测试:http://fiddle.jshell.net/6qMj8/1/