2013-05-20 28 views
3

我遇到了這個腳本的問題,我想用字段中的Hello World來實時替換輸入字段中輸入的任何字符。用jQuery實時替換輸入

<input id="inputID" type="text" value="" maxlength="11"/> 
$('#inputID').keyup(function(e){ 
    var cv=["h","e","l","l","o"," ","w","o","r","l","d",""]; 

    var i=$('#inputID').val(); 

    for (j=0;j<11;j++){ 

    this.value = this.value.replace(i[j],cv[j]); 

} 

}); 

這個腳本在我寫得很慢的時候效果很好,但是當我寫得很快的時候,這個腳本效果不錯。 感謝您的幫助

+0

所以每次按鍵更換信的11倍? – tymeJV

回答

3

嘗試這樣

$('#inputID').keyup(function(e){ 
    var cv = 'hello world'; 
    this.value = cv.substr(0, this.value.length); 
}); 

See the working demo.

+0

正確和緊湊。只有我會改變的是substr子字符串,但那真的很小, –

+0

工作正常,謝謝 – Netshad

-1

香草JavaScript讓所有人都很快與大量事件混淆。

jQuery在隊列中爲您排定動作,以便它們在適當的範圍內執行。

$('#inputID').keyup(function(e){ 
    var cv=["h","e","l","l","o"," ","w","o","r","l","d",""]; 

    var i=$('#inputID').val(); 

    for (j=0;j<11;j++){ 

    $(this).val($(this).val().replace(i[j],cv[j])); 

} 
}); 

小提琴:http://jsfiddle.net/Xedus129/MenpW/

+0

「The vanilla Javascript this gets all confused with many events quickly。」什麼?你認爲你的7行解決方案包括用'.val($(this).val()。replace()...'運行for循環嗎?'比我的4行香草草案(更短,但少教,)?如果是這樣,怎麼樣? –

+0

@BenjaminGruenbaum我從來沒有聲稱它是更清潔或更快,我只是解決了代碼有問題。 –

1

xdazz是如此lution是正確的(他打敗了我)

我覺得在展示一個不依賴於jQuery的解決方案可能會有好處,因此不想依賴它的用戶也能受益。

document.getElementById('inputID').onkeyup = function() { 
    var cv = "hello world"; // Your 'correct value' 
    //Set the value to a substring of cv at the current length 
    this.value = cv.substring(0, this.value.length); 
}; 

http://jsfiddle.net/9yfCe/

0

這是一樣快,我可以與KEYUP保持事件得到它:

var hw = "hello world"; 
$('#inputID').keyup(function(e){ 
    this.value = hw.substring(0, this.value.length); 
}); 

Demo

編輯:我相當驚訝三個人提出了幾乎完全相同的解決方案。真的很酷。

編輯2:我調整了一下,使其替換最初鍵入的字符,以幫助減少被替換字母的效果。

var hw = "hello world"; 
$('#inputID').keydown(function (e) { 
    if (e.which !== 8) { // allow backspace 
     e.preventDefault(); 
     this.value += ' '; 
    } 
}).keyup(function() { 
    this.value = hw.substring(0, this.value.length); 
}); 

Second demo