2013-01-21 29 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

非常感谢! –

相关问题