2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!

Fork me on GitHub

搜索框的联想功能实现

很简单的一个联想功能,直接贴代码!

$(function () {
    autoThink();
    
})

function autoThink() {
    var productArry = ["iphone6Plus", "mx3", "mx4", "mi3", "mi4", "minote"];
    var showArry = [];
    $("#serach").keyup(function () {
        showArry.splice(0, showArry.length); //清空数组 
        var searchVal = $(this).val();
        for (var i = 0; i < productArry.length; i++) {
            if (productArry[i].match(searchVal)) {
                showArry.push(productArry[i]);
            }
        }
        var innerhtml = "";
        innerhtml += "<ul style='list-style:none';font-size:13px>";
        for (var j = 0; j < showArry.length; j++) {
            innerhtml += "<li class='attchColor' onclick='getLi(this)' style=' cursor:pointer;'> " + showArry[j] + "</li>";
        }
        innerhtml += "</ul>";
        $("#autoLi").html(innerhtml);
        $("#autoLi").css("display","block");
    })

    $("#autoLi").focusout(function () {
        $("#autoLi").css("display", "none");
   })
    
        
}

function getLi(obj) {
    $("#serach").val(obj.innerHTML);
}

这里涉及到几个知识点:正则表达式,match()的使用。正则表达式在我前面的文章里面有了较为详细的说明,这里不再赘述!

下面说说match();

1.老规矩先:定义与用法

match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。

2.语法:

stringObject.match(searchvalue)
stringObject.match(regexp)

3.参数

(searchvalue,regexp)
 searchvalue:必需。规定要检索的字符串值。
 regexp:必需。规定要匹配的模式的 RegExp 对象。如果该参数不是 RegExp 对象,则需要首先把它传递给 RegExp 构造函数,将其转换为 RegExp 对象。

4.实例:

a:

<script type="text/javascript">

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

</script>

//对Hello world!进行检索

//输出
world
null
null
world!

b:

<script type="text/javascript">

var str="1 plus 2 equal 3"
document.write(str.match(/\d+/g))

</script>
//使用全局匹配的正则表达式来检索字符串中的所有数字

//输出
1,2,3

说明:其中g是对所有进行检索 其中涉及到简单的正则;不知道的可以看我文章<JavaScript 读书笔记三>之replace()与正则

posted on 2015-05-16 13:25  qize  阅读(3924)  评论(0编辑  收藏  举报

导航