2017-10-20 64 views
0

因此,我沒有發現在網上找到這個獨特的情況,所以我現在要問。在單獨的HTML頁面中的文本搜索加載到DIV

我有一個空的DIV作爲一個「容器」來保存和顯示一個'外部'HTML文檔。

<div id="page-content-wrapper" style="border: medium solid #000000; height:660px"> 
     <!--Loaded content goes here--> 
</div> 

在此頁面的邊欄中列出了用戶可以從中選擇的文檔(HTML文檔)。
有Javascript可以將選定的'external'HTML文檔加載到DIV(page-content-wrapper)中。
對於該SidebarItemClick方法的代碼是:

function MenuClick(doc) { 
    var Tutorial = doc; 
    var DisplayObj = "<object id='ThisObj' type='text/html' data='" + Tutorial + "' style='min-width:100%; min-height: 101%; overflow: hidden'></object>"; 
    document.getElementById("page-content-wrapper").innerHTML = DisplayObj; 
} 

這工作正常。該文檔很好地顯示在網頁上。

注意:從代碼中可以看出,由於各種原因,我沒有使用iFrame--主要是因爲我的老闆說「NO IFRAME」。注2:即使我可以在DIV(page-content-wrapper)內的網頁上看到正在顯示的「外部」HTML文檔 - 當我在那個時候檢查Page Source時,文本'外部'HTML文檔沒有出現 - 儘管

現在我想放在一起的一些Javascript,使用戶能夠搜索該'外部'HTML文檔中的文本,並滾動(如果需要)'發現'文本網頁的可見部分。

正如我在開始時所說的,目前在網上找到的東西似乎沒有解決這種情況,所以我希望有人有一個可行的方法。

您的意見/建議將不勝感激。

謝謝

+0

「外部html」在加載到'div'時成爲DOM的一部分,並且可以像其他任何DOM結構一樣處理。 – Mouser

+0

此外,我們需要看到一個生動的例子,以進一步幫助您。 – Mouser

+1

既然你說文檔很好地顯示在網頁上,普通的瀏覽器搜索應該足以搜索和定位文本,不是嗎? –

回答

0

這是我嘗試(不成功)使用的搜索代碼。注意:評論中途代碼下來就如何執行:

function findInContent() { 
    // Get User Input text 
    var needle = document.getElementById('txtSearch').value; 
    var n = 0; 
    var txt, i, found; 
    if (needle == "") { 
     // If nothing entered, get out 
     return false; 
    } 

    // Find next occurance of the given string on the page, wrap around to 
    // the start of the page if necessary. 
    var sourceObj = document.querySelector("#ThisObj"); 
    // NOTE: the sourceObj is found and is the ID of the 'external' document 
    var sourceBody = sourceObj.contentDocument.body; 
    // NOTE: At this point, <this> = #ThisObj 
    // and during in-house testing 
    //  <this>.data = "http://localhost6017/tutorials/Cashiering.htm" 
    // which is the dynamically loaded 'external' document. 
    // but after this everything 'falls apart' because none of the rest 
    // is defined. 
    var haystack = sourceBody.innerHTML; // This comes up empty 

    var match = haystack.indexOf(needle); 
    if (match != -1) { 
     // --- Match Found --- 
     //console.log(match); 
     var innerHTML = haystack.substring(0, match) 
      + "<span class='highlight'>" + haystack.substring(match, match + needle.length) + "</span>" 
      + haystack.substring(match + needle.length); 
     sourceBody.innerHTML = innerHTML; 
    } else { 
     // --- Match NOT Found --- 
     //console.log('Not Found'); 
    } 
    return false; 
} 

希望有人能就如何修改勸我/改變findInContent()(搜索)代碼找到用戶輸入的文本(以下簡稱「針'')在「外部」文件中。

謝謝

+0

任何關於在上面的findInContent()代碼中修改什麼的新建議/建議,以使其發揮作用?請注意,這些註釋表明代碼的作用以及在什麼時候事情開始「分崩離析」。 – Dhugalmac

相關問題