简体   繁体   中英

Load a Javascript function when typing something certain up until a space

For example: When someone types @ it will ready the function.

On Twitter for example, shows something when someone types @USERNAME then after the space, they don't show anything.

Here an javascript example:

document.getElementById('test').onkeyup = function(oEvent) {
    if (typeof oEvent == 'undefined') oEvent = window.event;          // IE<9 fix
    if (oEvent.keyCode != 32) return;       // stop if character is not the space
    if (/@USERNAME /.test(this.value)) {      // check if @-template is available
        this.value = this.value.replace(/@USERNAME /g, 'Dirk ');    // replace it
    }
}

Also see this jsfiddle .

=== UPDATE ===

Here an jQuery alternative:

$('#test').keyup(function(oEvent) {                  // set (keyup) event handler
    if (oEvent.keyCode != 32) return;       // stop if character is not the space
    if (/@USERNAME /.test($(this).val())) {   // check if @-template is available
        $(this).val($(this).val().replace(/@USERNAME /g, 'Dirk ')); // replace it
    }
});

Also see this jsfiddle .

也许您可以在按下空格键时尝试onkeypress事件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM