JavaScript window.find 绝对不能正常工作 [英] JavaScript window.find doesn't work absolutely

查看:18
本文介绍了JavaScript window.find 绝对不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试传递分布在几个块元素中的文本时,window.find 方法会起作用:

When I try to pass text which spreads throughout a few block elements the window.find method dosent work:

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
  <p>search me</p><b> I could be the answer</b>
</body>
</html>

JavaScript:

window.find("meI could be");

或者:

str = "me";
str+= "
";
str+="I could be t";

window.find(str);

<p> 元素出现在搜索词之间时会发生这种情况.

This happens when the <p> element is present between the search term.

我该如何解决这个问题?

How can I fix that?

推荐答案

作为选项:

function containsStr(str) {
    return document.body.innerText.indexOf(str) > -1;
}

刚刚对其进行了测试,它的工作原理与 window.find 相同.或 window.find 与我的功能相同.无论如何,这似乎取决于元素的 style.display 属性.例如.当我设置

Just tested it and it's working same as window.find. Or window.find is working same as this my function. Anyway seems it's depends to element's style.display property. E.g. when I set

p {
    display: inline;
}

此调用 window.find("me I could be") 为您的 HTML 示例返回 true.

this call window.find("me I could be")​ returns true for your HTML example.

我创建了 this example 来测试提到的行为.
作为选项,您可以在内存中创建一个 div 元素,获取 document.body.innerHTML 并将检索到的值设置为 div 的 innerHTML,然后更改 style.dysplay"inline" 以查找此 div 中的元素,类似于我在代码示例中所做的,然后执行搜索.

I created this example to test mentioned behavior.
As option you can create a div element in memory, get document.body.innerHTML and set retrieved value to div's innerHTML, then change style.dysplay to "inline" for elements within this div similar to what I did in my code example, and then perform a search.

更新 #1:jQuery

我做了更深入的研究,发现使用 jQuery :contains 选择器比我之前的函数和 window.find 工作得更好,但可能更贵(不确定,需要测试).

I've made deeper research and found that usage of jQuery :contains selector is working better than my previous function and than window.find, but may be more expensive (not sure, need to be tested).

function containsStr$(str) {
    return $('body:contains("'+str+'")').length > 0;
}

更新 #2:纯 JavaScript 解决方案

function _find(str) {
    var div = document.createElement('div');
    div.innerHTML = document.body.innerHTML;
    var elements = div.getElementsByTagName('*');
    for(var i = elements.length; 0 > i--;) {
        elements[i].style.display = 'inline';
    }
    return (div.innerText || div.textContent).indexOf(str) > -1;
}

这篇关于JavaScript window.find 绝对不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆