无法确定字符串是否包含数组中的单词

The*_*see 7 html javascript arrays jquery

我试图通过使用jQuery的inArray函数来确定一个字符串是否包含来自数组的单词,这里显示的是/sf/answers/1320736721/

在我下面的例子中,它应该向控制台打印'hi'两次,因为单词'Hello'在字符串中两次并且在数组中,但它没有.

var array = ["Hello", "Goodbye"];

a = document.getElementsByClassName("here");

for (i = 0; i < a.length; i++) {
  itag = a[i].getElementsByTagName("i")[0];
  if (jQuery.inArray(itag.innerHTML, array) !== -1) {
    console.log('hi');
  }
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="here"><i><a href="link.php">Hello</a> | <a href="link2.php">Example</a></i>
</div>

<div class="here"><i><a href="link.php">Hey</a> | <a href="link2.php">Hello</a></i>
</div>
Run Code Online (Sandbox Code Playgroud)

Sur*_*yan 8

改变inArray功能array.some(text => itag.textContent.includes(text)).

通过声明所有变量var or const or let.

而不是innerHTML使用textContent.这不会尝试解析内容并且会更快地工作.

var array = ["Hello", "Goodbye"];

var a = document.getElementsByClassName("here");

for (var i = 0; i < a.length; i++) {
    var itag = a[i].getElementsByTagName("i")[0];
    var textContent = itag.textContent;
    if(array.some(text => textContent.includes(text))) {
       console.log(textContent);
    }
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="here"><i><a href="link.php">Hello</a> | <a href="link2.php">Example</a></i>
</div>

<div class="here"><i><a href="link.php">Hey</a> | <a href="link2.php">Hello</a></i>
</div>
Run Code Online (Sandbox Code Playgroud)