📜  搜索关键字 jquery - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:01:47             🧑  作者: Mango

代码示例1
// Search functionality
function myFunction() {
    // Declare variables
    var input = document.getElementById('myInput'),
        filter = input.value,
        ul = document.getElementById('myUL'),
        lis = ul.getElementsByTagName('li'),
        searchTerms = filter.match(/[a-z]+/gi),
        re, index, li, a;
        
    if (searchTerms) {
        searchTerms = searchTerms.map(function(term) {
            return '(?=.*' + term + ')';
        });
        
        re = new RegExp(searchTerms.join(''), 'i');
    } else {
        re = /./;
    }

    // Loop through all list items, and hide those who don't match the search query
    for (index = 0; index < lis.length; index++) {
        li = lis[index];
        a = li.firstChild;

        if (re.test(a.innerHTML + ' ' + a.getAttribute('data-keywords'))) {
            li.style.display = '';
        } else {
            li.style.display = 'none';
        }
    }
}