开发者

javascript - multiple CreateTextRange simultaniously

I h开发者_如何学编程ave the below javascript function, which when passed a word such as "Department" will highlight in red the first instance of "Department" found on the screen. However, i would like this code to highlight ALL instances of the given word.

function findString (str) { 
    var TRange=null;
    var strFound; 
    var TRange = self.document.body.createTextRange();
    TRange.findText(str);
    TRange.execCommand('foreColor', false, "#ff0000");
    return;
} 


function findString (str) { 
    var TRange = document.body.createTextRange();

    while (TRange.findText(str)){
        TRange.execCommand("foreColor", false, "#ff0000");
        TRange.collapse(false);
    }
}


function findString (str) { 
    var TRange=null;
    var strFound; 
    var TRange = self.document.body.createTextRange();

    while(TRange.findText(str))
    {
        TRange.execCommand('foreColor', false, "#ff0000");
    }

    return; 
    } 


This code seems to have done it, but it is sloppy and a little excessive. I'm sure there must be a shorter way to do it rather than almost duplicating my execCommand line twice in the same function.

var TRange=null;
function findString (str) { 

    var strFound; 
    var counter = 0;

    if (TRange==null || strFound==0) {
            TRange=self.document.body.createTextRange()  
            strFound=TRange.findText(str) 
            if (strFound) {
                TRange.execCommand('foreColor', false, "#ff0000");
            }
    } 

    TRange.collapse(false);
    while (strFound=TRange.findText(str)) {
        if (counter > 50){
            alert("Search exceeded maximum limit of 50.");
            return;
        }
        TRange.execCommand('foreColor', false, "#ff0000");
        TRange.collapse(false); 
        counter += 1;
    }

    return;
} 


Take a look at this link: http://www.nsftools.com/misc/SearchAndHighlight.htm

The script used on that page is a different approach to what you're taking but the end result is exactly what you're looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜