javascript 如何在javascript中编写onblur和onfocus事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5014710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:40:15  来源:igfitidea点击:

how to write onblur and onfocus event in javascript?

javascriptjquery

提问by gomzi

Question:

问题

 <body onload="setBlurFocus()">   
     <form method="POST" action="#">   
              <input id="id_username" type="text" name="username" maxlength="100" />
              <input type="text" name="email" id="id_email" />
              <input type="password" name="password" id="id_password" /> 
        </form> 
    </body>

I wrote:

写道

function setBlurFocus () {
    var user_input = document.getElementById('id_username');
    var email = document.getElementById('id_email');
    var password = document.getElementById('id_password');
    user_input.onblur = userSetBlur();
    email.onblur = emailSetBlur();
    password.onblur = passSetBlur();
    user_input.onfocus = function() {
            document.getElementById('id_username').value = ''   
        }
    email.onfocus = function() {
            document.getElementById('id_email').value = ''  
        }
    password.onfocus = function() {
            document.getElementById('id_password').value = ''   
        }

}

function userSetBlur() {
    document.getElementById('id_username').value = 'Username'
}
function emailSetBlur() {
    document.getElementById('id_email').value = 'Email'
}

function passSetBlur() {
    document.getElementById('id_password').value = 'Password'
}

Question?How to generalizeor optimizedthis code?

问题?如何generalizeoptimized此代码?

回答by Felix Kling

You can always attach the methods in JavaScript:

您始终可以在 JavaScript 中附加这些方法:

function setBlurFocus() {
    var user_input = document.getElementById('id_username');
    user_input.onblur = someFunction;
    // or with an anonymous function:
    user_input.onfocus = function() {
        // do something
    }
}

Read more about traditional event handlingand events in general.

阅读有关传统事件处理一般事件的更多信息。



Further explanation:

进一步解释:

You attached the function setBlurFocusto the loadevent of the document. This is correct if you have to access DOM elements with JavaScript. The loadevent is fired when all the elements are created.

您将函数附加setBlurFocusload文档的事件。如果您必须使用 JavaScript 访问 DOM 元素,这是正确的。load创建所有元素时会触发该事件。

If you attach the setBlurFocus()to the blurevent of the inputfield, then the function is only executed when the text box looses focus.

如果将 附加setBlurFocus()到字段的blur事件input,则该函数仅在文本框失去焦点时执行。

From your question I concluded you don't want set the event handlers in the HTML, but you want to set them form inside the setBlurFocusfunction.

从你的问题我得出结论,你不想在 HTML 中设置事件处理程序,但你想在setBlurFocus函数内部设置它们。



Regarding your update:

关于你的更新:

This is wrong:

这是错误的:

user_input.onblur = userSetBlur();

This assigns the return valueof the function to onblur. You want to assign the function itself, so you have to write:

这将函数的返回值分配给onblur。你想分配函数本身,所以你必须写:

 user_input.onblur = userSetBlur;

The ()callsthe function. You don't want that (in most cases, there are exceptions, see below).

()调用该函数。你不希望那样(在大多数情况下,有例外,见下文)。

Furthermore, you don't have to use named functions for onblurand anonymous functions for onfocus. It was just an example, to show you the different possibilities you have. E.g. if you assign an event handler to only one element, then there is no need to define it as extra function. But you have to do this if you want to reuseevent handlers.

此外,您不必为 使用命名函数onblur和匿名函数onfocus。这只是一个例子,向您展示您拥有的不同可能性。例如,如果您仅将事件处理程序分配给一个元素,则无需将其定义为额外的函数。但是如果你想重用事件处理程序,你必须这样做。

Here is an improved version:

这是一个改进的版本:

function setBlurFocus () {
    var values = ["Username", "Email", "Password"];
    var elements = [
        document.getElementById('id_username'),
        document.getElementById('id_email'),
        document.getElementById('id_password')
    ];

    for(var i = elements.length; i--; ) {
        elements[i].onblur = setValue(values[i]);
        elements[i].onfocus = emptyValue;
    }
}

function setValue(defaultValue) {
    return function(){this.value = defaultValue;};
}

function emptyValue() {
    this.value = '';
}

thisinside the event handlers refers to the element the handler is bound to.

this事件处理程序内部是指处理程序绑定到的元素。

Note:Here setValuereturns a function, that is why we call setValuein this case (and not just assign it).

注意:这里setValue返回一个函数,这就是我们setValue在这种情况下调用的原因(而不仅仅是分配它)。

Important note:This will also reset the values to Usernameetc, if the user entered some data. You have to make sure, that you only reset it if the user has not entered data. Something like:

重要说明:Username如果用户输入了一些数据,这也会将值重置为等。您必须确保只有在用户未输入数据时才重置它。就像是:

function setValue(defaultValue) {
    return function(){
        if(this.value !== "") {
            this.value = defaultValue;
        }
    };
}

and you'd have to define emptyValuesimilar:

你必须定义emptyValue类似的:

function emptyValue(defaultValue) {
    return function(){
        if(this.value === defaultValue) {
            this.value = "";
        }
    };
}


Now that I know what you actually want to do, have also a look at HTML5's placeholderattribute.

现在我知道你真正想要做什么,也看看HTML5 的placeholder属性

回答by aiham

Well you've tagged it with jquery so this is how to do it in jquery:

好吧,你已经用 jquery 标记了它,所以这是在 jquery 中的做法:

function setBlurFocus () {
  //do stuff here
} 

$('#id_username').blur(setBlurFocus);

or

或者

$('#id_username').blur(function(){
    //do stuff here
});

回答by quocnguyen

Regarding your update

关于你的更新

I using jquery as you tab jquery, the code was bellow , you can check a live sample with this link :

我在 Tab jquery 时使用 jquery,代码如下,您可以使用此链接查看实时示例:

http://jsfiddle.net/e3test/zcGgz/

http://jsfiddle.net/e3test/zcGgz/

html code :

html代码:

<form method="POST" action="#">   
             <input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" /> 
</form> 

javascript code :

javascript代码:

$(function(){
    var selector = {
        username: $('#id_username'),
        email: $('#id_email'),
        password: $('#id_password')
    };

    for (var x in selector) {
        selector[x].focus(function(){
           $(this).val('');
        }).blur(function(){
            $(this).val($(this).attr('name'));
        });
    }
});

Hope it help.

希望有帮助。