javascript 检查字符串中的第一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6348325/
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
Check First Char In String
提问by daGrevis
I have input-box. I'm looking for a way to fire-up alert()
if first character of given string is equal to '/'...
我有输入框。alert()
如果给定字符串的第一个字符等于'/',我正在寻找一种启动方法...
var scream = $( '#screameria input' ).val();
if ( scream.charAt( 0 ) == '/' ) {
alert( 'Boom!' );
}
It's my code at the moment. It doesn't work and I think that it's because that browser doesn't know when to check that string... I need that alert whenever user inputs '/' as first character.
这是我目前的代码。它不起作用,我认为这是因为该浏览器不知道何时检查该字符串...每当用户输入“/”作为第一个字符时,我都需要该警报。
回答by Naftali aka Neal
Try this out:
试试这个:
$( '#screameria input' ).keyup(function(){ //when a user types in input box
var scream = this.value;
if ( scream.charAt( 0 ) == '/' ) {
alert( 'Boom!' );
}
})
回答by maerics
You need to add a keypress (or similar) handler to tell the browser to run your function whenever a key is pressed on that input field:
您需要添加一个按键(或类似)处理程序,以告诉浏览器在该输入字段上按下某个键时运行您的函数:
var input = $('#screameria input');
input.keypress(function() {
var val = this.value;
if (val && val.charAt(0) == '/') {
alert('Boom!');
}
});