jquery中的indexOf方法?

时间:2012-06-05 08:18:19

标签: jquery html

我在var名称“str”中丢失了特殊字符现在我希望用户在其中输入字符,然后提醒他“hiii”其他“byeee”,具体取决于字符串的检查索引

<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
    $('#me').click(function(){
    var Amd=$('.text').val();

    var str="[,],{,},<,>"

    if(Amd.indexOf(str)>-1){

        alert('hiiiii')

        }       
    else {
        alert('byee')
        }
    })
    })
</script>
</head>
<body>
<input type="text" class="text" />
<input type="button" value="click" id="me"/>
</body>

3 个答案:

答案 0 :(得分:3)

你可以使用正则表达式匹配来做到这一点,顺便说一句,你应该为每一行添加;,这是一个好习惯。

$(function () {
    $('#me').click(function () {
        var Amd = $('.text').val();
        if (Amd.match(/[\[\]{}<>]/)) {
            alert('hiiiii');
        } else {
            alert('byee');
        }
    });
});

答案 1 :(得分:1)

使用RegExp

if( Amd.match(new RegExp(/[\[\]\{\}<>]/)) ) {
....

答案 2 :(得分:0)

检查一下。

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  span { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){

    $('#me').click(function(){
    var Amd=$('.text').val();

    var str="\[,],{,},<,>";
    var n=Amd.indexOf(str);
    if(n>-1)
    {
       alert("Hi");
    }
    else
       alert("Bye");

    });
    });
</script>
</head>
<body>
<input type="text" class="text" />
<input id="me" value="Click Me" type="button" />

</body>
</html>

如果您想检查任何符号,例如“或{或[双引号(”“)中的任何内容,请在该符号前加\