我试图通过使用 jQuery 的 inArray
函数来确定字符串是否包含数组中的单词,此处显示了 https://stackoverflow.com/a/18867667/5798798
在我下面的示例中,它应该向控制台打印两次“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');
}
}
<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>
最佳答案
将 inArray
函数更改为 array.some(text => itag.textContent.includes(text))
。
通过 var 或 const 或 let
声明所有变量。
使用 textContent
代替 innerHTML
。这不会尝试解析内容
并且会工作得更快。
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);
}
}
<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>
关于javascript - 无法确定字符串是否包含数组中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044666/