我遇到了一个问题: 我想在 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);
}
}
}
谢谢大家! 亚当
最佳答案
将上面评论中的代码放入代码标签中,以提高可读性。
$(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"));
}
关于javascript - 通过内部文本获取所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14438820/