简体   繁体   English

检查字符串中的第一个字符

[英]Check First Char In String

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.它不起作用,我认为这是因为该浏览器不知道何时检查该字符串......每当用户输入“/”作为第一个字符时,我都需要该警报。

Try this out:试试这个:

$( '#screameria input' ).keyup(function(){ //when a user types in input box
    var scream = this.value;
    if ( scream.charAt( 0 ) == '/' ) {

      alert( 'Boom!' );

    }
})

Fiddle: http://jsfiddle.net/maniator/FewgY/小提琴: http://jsfiddle.net/maniator/FewgY/

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:您需要添加一个按键(或类似)处理程序来告诉浏览器在该输入字段上按下一个键时运行您的 function:

var input = $('#screameria input');
input.keypress(function() {
  var val = this.value;
  if (val && val.charAt(0) == '/') {
    alert('Boom!');
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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