首页 > 解决方案 > 如何使用 JavaScript 在 HTML 页面中查找文本?

问题描述

我下面的代码试图在页面上的任何位置找到文本“Hello mate”,如果存在则显示警报。

var array = Array.from(document.querySelectorAll('div'))
      .find(el => el.textContent.includes("Hello mate"));
      if (array){
        alert("hi!")
}

它没有给出错误,但是没有出现警报。有什么建议么?

标签: javascripthtml

解决方案


$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });

  var array = Array.from(document.querySelectorAll('div'))
      .find(el => el.textContent.includes("Hello mate"));
      if (array){
        alert("hi!")
  }
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="source_your_file"></script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

<div>Hello mate</div>

</body>
</html>

也许你错过了在你的标题上添加你的文件 jquery 或者你的 jquery 首先需要调用 $(document).ready(function(){} 。我有使用 jquery 的例子,也许它可以帮助你


推荐阅读