簡體   English   中英

鍵入某些特定內容(直到空格)時,加載Javascript函數

[英]Load a Javascript function when typing something certain up until a space

例如:當有人鍵入@ ,它將准備好函數。

例如,在Twitter上,當某人鍵入@USERNAME時顯示一些內容,然后在空格后不顯示任何內容。

這是一個JavaScript示例:

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
    }
}

另請參閱此jsfiddle

===更新===

這里是jQuery的替代品:

$('#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
    }
});

另請參閱此jsfiddle

也許您可以在按下空格鍵時嘗試onkeypress事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM