2012-10-11 54 views
0

我需要在我正在處理的網站中放置搜索頁面功能。我發現一個在線,它在Firefox和Chrome中很好用,但在IE中完全沒有。我認爲我沒有寫這段代碼的事實讓它特別難以調試。任何幫助或指導表示讚賞!因特網瀏覽器的搜索頁面功能

HTML

<form id="f1" name="f1" action="javascript:void(0)" onsubmit="searchpage()" > 
<input id="t1" type="text" name="t1" /> 
<input id="button" type="submit" value="FIND" name="b1" onclick="searchpage()" /> 
</form> 

JAVASCRIPT

function searchpage() { 
    if (document.getElementById("t1").value != null && this.document.getElementById("t1").value != '') parent.findString(document.getElementById("t1").value); 
    return false; 
} 
var TRange = null; 

function findString(str) { 
    if (parseInt(navigator.appVersion) < 4) return; 
    var strFound; 
    if (window.find) { 
     // CODE FOR BROWSERS THAT SUPPORT window.find 
     strFound = self.find(str); 
     if (!strFound) { 
      strFound = self.find(str, 0, 1); 
      while (self.find(str, 0, 1)) continue; 
     } 
    } 
    else if (navigator.appName.indexOf("Microsoft") != -1) { 
     // EXPLORER-SPECIFIC CODE 
     if (TRange != null) { 
      TRange.collapse(false); 
      strFound = TRange.findText(str); 
      if (strFound) TRange.select(); 
     } 
     if (TRange == null || strFound == 0) { 
      TRange = self.document.body.createTextRange(); 
      strFound = TRange.findText(str); 
      if (strFound) TRange.select(); 
     } 
    } 
    else if (navigator.appName == "Opera") { 
     alert("Opera browsers not supported, sorry...") 
     return; 
    } 
    if (!strFound) alert("String '" + str + "' not found!") return; 
}​ 

同樣重要的是要注意的是,雖然這部作品在Firefox和Chrome,在 「字符串沒有找到!」警示框不起作用

回答

1

以下是從another answer of mine完成的版本。

演示:http://jsfiddle.net/MRp2G/5/

代碼:

function doSearch(text) { 
    var sel; 
    if (window.find && window.getSelection) { 
     sel = window.getSelection(); 
     if (sel.rangeCount > 0) { 
      sel.collapseToEnd(); 
     } 
     window.find(text); 
    } else if (document.selection && document.body.createTextRange) { 
     sel = document.selection; 
     var textRange; 
     if (sel.type == "Text") { 
      textRange = sel.createRange(); 
      textRange.collapse(false); 
     } else { 
      textRange = document.body.createTextRange(); 
      textRange.collapse(true); 
     } 
     if (textRange.findText(text)) { 
      textRange.select(); 
     } 
    } 
} 
+0

哇!非常感謝!在我所有的搜索中,我找不到它!謝謝你的協助! – daniella

+0

所以現在我試圖用選項做一個下拉列表,以便您可以搜索表中的特定類別。我有所有按ID排序的列。任何想法如何去做這件事? – daniella

+0

@ user1634292:哪一位讓你失望? –