我找不到在子字符串中搜索字母/字符串的方法。目的是在找到该字符串时创建警报。谢谢
https://jsfiddle.net/1rawcotx/2/
function validate() {
if (string.indexOf('worlds') > -1) {
alert("word found");
}
}
<div id="string">
worlds and some other text
</div>
<button id="button" onclick="validate()">click me</button>
最佳答案
DOM 元素没有 indexOf
,但在您的示例中,string
是 DOM 元素,因为您使用的是自动全局 通过提供您的 div
id="string"
创建。
要获取 div
的内容,您可以使用它的 innerHTML
或innerText
或textContent
属性。
我也不提倡使用自动全局变量(尽管它们现在在规范中),因为那里有太多相互冲突的全局变量。相反,我会明确使用 getElementById
:
function validate() {
if (document.getElementById("string").innerHTML.indexOf('worlds') > -1) {
alert("word found");
}
}
<div id="string">
worlds and some other text
</div>
<button id="button" onclick="validate()">click me</button>
关于javascript - 使用 javascript 检查字符串中是否包含单词/字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862884/