2013-01-21 28 views
1

我遇到了問題: 我想在html文檔中搜索字符串。到目前爲止,我嘗試使用window.find(..)方法,但我無法找回找到的元素的節點。舉個例子,我可以突出顯示所有匹配的文本。 但我想把所有的節點放在一個數組中,我找不到一個方法,它可以返回所選文本的節點。 以下代碼僅突出顯示匹配的文本,我想獲取它的(父)節點。通過內部文本獲取所有元素

function doSearchAdam(text) { 
if (window.find && window.getSelection) { 
    document.designMode = "on"; 
    var sel = window.getSelection(); 
    sel.collapse(document.body, 0); 
    while (window.find(text)) { 
     document.execCommand("HiliteColor", false, "yellow"); 
     sel.collapseToEnd(); 
    } 
    document.designMode = "off"; 
} else if (document.body.createTextRange) { 
    var textRange = document.body.createTextRange(); 
    while (textRange.findText(text)) { 
     textRange.execCommand("BackColor", false, "yellow"); 
     textRange.collapse(false); 
    } 
} 

}

謝謝你們! Adam

+0

你可以使用jQuery嗎?那麼你可以做類似於http://stackoverflow.com/questions/7486282/jquery-select-by-inner-text – Rhumborl

+0

是的,謝謝!很有用!下面是代碼,如果有人在不知道有關解決方案: 「$(文件)。就緒(函數(){ \t $( 「#findButton」)點擊(函數(){ \t \t myFunction的(); \t}); }); function myFunction(){ \t var matchedPages = new Array(); ($(this).text()。indexOf($(「#findText」)。val())> = 0){//$( 「#FINDTEXT」)值() \t \t \t的console.log($(本)); \t \t \t matchedPages.push($(本)); \t \t} \t}); \t console.log(matchedPages); \t console.log(matchedPages [1] .attr(「id」)); }' –

回答

0

將上述註釋中的代碼放置到代碼標記中以提高可讀性。

$(document).ready(function() { 
    $("#findButton").click(function() { 
     myFunction(); 
    }); 
}); 

function myFunction() { 
    var matchedPages = new Array(); 
    $(".Page").filter(function() { 
     if ($(this).text().indexOf($("#findText").val()) >= 0) { 
      //$("#findText").value() console.log($(this)); 
      matchedPages.push($(this)); 
     } 
    }); 
    console.log(matchedPages); 
    console.log(matchedPages[1].attr("id")); 
} 
+0

非常感謝! –

相關問題