搜索框的聯想功能實現


很簡單的一個聯想功能,直接貼代碼!

$(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()與正則


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM