JavaScript中trim 、indexOf

本文介绍了一个类似百度搜索功能的JavaScript实现方法,详细讲解了trim()和indexOf()函数的应用,并通过实例演示了如何在输入框中实时搜索匹配数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


实现类似于百度搜索的功能一样
trim()作用 :$.trim() 函数返回值为 String 新增静态函数,去除两端空白字符串后的字符;  例如输入的“李”字前有空格,通过trim方法的作用,就会忽略(去掉 空白字符(空格)


indexOf 作用:
<html>
<body>

<script type="text/javascript">

var str="Hello world!"
document.write(str.indexOf("Hello") + "<br />")
document.write(str.indexOf("World") + "<br />")
document.write(str.indexOf("world"))

</script>

</body>
</html>
中为什么显示的是3个数字呢?

解释:
它所查出来的是你给的母字符串(也就是str)中某一个字符的下标位置,比如第一个Hello在 
Hello world中 Hello的第一个字符H在第一位,因为 从0开始算的,所以输出0。 而第二个因为在Hello world中查找World(注意大小写w),所以没有,大小写敏感的。所以返回-1,最后一个就不用解释了,空格也占用一个字符的位置






< script>
function getContent(obj){
       $( "#a" ).hide();
           $( "#b" ).hide();
           $( "#c" ).hide();
           /* $.trim() 函数返回值为 String 新增静态函数,去除两端空白字符串后的字符 */
    var kw = jQuery.trim($(obj).val());
    if (kw == "" ){
        $( "#append" ).hide().html( "" );
        return false ;
    }
    var html = "" ;
   
/****
indexOf() 的作用: indexOf()方法是指字符串的开始位置,索引 从0开始,比如你的indexOf("Hello"),返回就是0,而第二个大小写不一样,就没有找到这个字符串,则返回-1,第三个就返回2,因为中间有个空格
****/
    for ( var i = 0; i < data.length; i++) {

/* data[i].indexOf(kw) >= 0   通过indexOf方法从data[i]中搜索数据  */

        if (data[i].indexOf(kw) >= 0) {
            html = html + "<div class='item' οnmοuseenter='getFocus(this)' onClick='getCon(this," +i+ ");' style='height:30px'>" + data[i] + "</div>"
 
        }
    }
    if (html != "" ){
        $( "#append" ).show().html(html);
    } else {
     searchUser();
        $( "#append" ).hide().html( "" );
    }
}
</ script>


<  html >
<  body >
      < tr >
                    < th > 客户信息: </ th >
                    < td >< input style =" margin-bottom : 0px " type = "text" name = "trueName" id = "trueName"   onKeyup = "getContent(this);" value = "" maxlength = "40" placeholder = "输入客户姓名进行查找" />
                   
                    < span id = "a" >< br >< input type = "text" name = "clientPhone" id = "clientPhone" value = "" maxlength = "40" placeholder = "输入客户姓名进行查找" disabled = "true" /></ span >
                    < span id = "b" >< br >
                    < input type = "text" name = "clientPhone" id = "clientEmail" value = "" maxlength = "40" placeholder = "输入客户姓名进行查找" disabled = "true" /></ span >
                    < span id = "c" >< br >
                    < input type = "text" name = "clientNickName" id = "clientNickName" value = "" maxlength = "40" placeholder = "输入客户姓名进行查找" disabled = "true" /></ span >
                    < div id = "append" ></ div >
                    </ td >
                   
               </ tr >
</  body >
</  html >













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值