搜索网站上的文字

时间:2012-12-10 10:33:25

标签: javascript html web-applications

受尊敬的会员,

我在一个模板的帮助下用纯HTML设计网站。

因为我有一个文本框[搜索]和Go按钮。

我想进行操作,以便当任何一种类型的某些文字按下Go按钮时, 它应该突出显示该网站中与该文本匹配的文本。

我该怎么做?

比你。

3 个答案:

答案 0 :(得分:11)

$(document).ready(function(){
        $('#searchItem').keyup(function(){
            var name = $(this).val();
            var pattern = name.toLowerCase(); 
            var targetId = ""; 
            var divs = document.getElementsByClassName("item"); 

            $(document).find('.item').hide();

            $('.item').each(function(i){
                var para = divs[i].getElementsByTagName("p"); 
                var index = para[0].innerText.toLowerCase().indexOf(pattern); 
                if (index != -1) { 
                    $(this).show();
                }
            });
        }); 
    });

答案 1 :(得分:5)

你没有张贴你的东西。我想这就是你提到的。

检查一下。我可以为你做这件事,但你必须在你的想法中做到这一点

function highlightInElement(elementId, text){
var elementHtml = document.getElementById(elementId).innerHTML;
var tags = [];
var tagLocations= [];
var htmlTagRegEx = /<{1}\/{0,1}\w+>{1}/;

//Strip the tags from the elementHtml and keep track of them
var htmlTag;
while(htmlTag = elementHtml.match(htmlTagRegEx)){
    tagLocations[tagLocations.length] = elementHtml.search(htmlTagRegEx);
    tags[tags.length] = htmlTag;
    elementHtml = elementHtml.replace(htmlTag, '');
}

//Search for the text in the stripped html
var textLocation = elementHtml.search(text);
if(textLocation){
    //Add the highlight
    var highlightHTMLStart = '<span class="highlight">';
    var highlightHTMLEnd = '</span>';
    elementHtml = elementHtml.replace(text, highlightHTMLStart + text + highlightHTMLEnd);

    //plug back in the HTML tags
    var textEndLocation = textLocation + text.length;
    for(i=tagLocations.length-1; i>=0; i--){
        var location = tagLocations[i];
        if(location > textEndLocation){
            location += highlightHTMLStart.length + highlightHTMLEnd.length;
        } else if(location > textLocation){
            location += highlightHTMLStart.length;
        }
        elementHtml = elementHtml.substring(0,location) + tags[i] + elementHtml.substring(location);
    }
}

//Update the html of the element
document.getElementById(elementId).innerHTML = elementHtml;
}

highlightInElement("fatDoggie","The dog is really really fat");

这个小提琴是为了突出显示一组文字而不是你应该在搜索中获取变量并放在highlightInElement("Element","Var");

答案 2 :(得分:1)

你的意思是你有一个单页的网站?在这种情况下,整个内容已经加载到页面上,您只想搜索它。你可以使用Javascript和JQuery轻松完成。只需点击按钮,然后遍历DOM寻找你的字符串,然后对其进行处理(例如,滚动直到那里,或突出显示它)。

如果您有多个页面,那么这将更具挑战性,因为您没有客户端可用的所有内容。在这种情况下,服务器端搜索解决方案会更好。