就像在Facebook上輸入評論時,您擊中@username時一樣,它會對此做出反應,讓您選擇內聯用戶名。在jQuery中,如何在用戶輸入時檢測指定的字符串?
使用jQuery,我們將如何爲[text:1]連接一個事件偵聽器。我想要在用戶輸入[text:
時觸發一個事件到文本字段中。
就像在Facebook上輸入評論時,您擊中@username時一樣,它會對此做出反應,讓您選擇內聯用戶名。在jQuery中,如何在用戶輸入時檢測指定的字符串?
使用jQuery,我們將如何爲[text:1]連接一個事件偵聽器。我想要在用戶輸入[text:
時觸發一個事件到文本字段中。
使用keyup
函數來觸發。拆分所有字符串並檢查它。
[更新]:更多的改進版
<script>
var totalcount=0;
$(function(){
$('#text').keyup(
function(){
var arr = $(this).val().split(" ");
var matchitems = count('hello', arr);
//console.log(matchitems);
if(matchitems > totalcount){
alert('hello');
totalcount = matchitems;
}
if(matchitems < totalcount)
{
totalcount = matchitems;
}
}
)
})
function count(value, array)
{
var j=0;
for(var i=0;i<array.length;i++)
{
if(array[i] == "hello"){
j++;
}
}
return j;
}
</script>
<input type="text" id="text" />
})
</script>
<input type="text" id="text" />
Zurb創建textchange插件,這將有助於。看到自己的「驗證文本」例如向底部,我認爲它幾乎正是你要尋找的..
http://www.zurb.com/playground/jquery-text-change-custom-event
真棒鏈接,謝謝! – Chaddeus 2011-03-07 06:33:07
使用keyup
像@experimentX提到的是你要去B中的路/ C,則你會知道你的用戶已經輸入了價值。但是,運行for
循環對於每一個鍵盤事件都是非常昂貴的。相反,因爲你知道你想已經是值,您可以使用預設regexp
搜索你的價值:
<input type="text" id="text" value="" />
<script>
$(function() {
var $input = $('#text');
$input.keyup(function (e) {
var regexp = /\[text\:/i,
val = $(this).val();
if (regexp.test(val)) {
console.log('i have it: ', val);
}
});
});
</script>
這裏是你如何編寫實際regexp
一對夫婦的其他方案。
var regexp = /^\[text\:/i;
var regexp = /^\s+?\[text\:/i;
謝謝,這很好! – Chaddeus 2011-03-07 06:32:50