我想寫一個段落,然后有一個搜索欄來查找段落中是否有給定的單詞。如果我在搜索欄中寫下“are”,它應該通過警報告訴我“該詞在文本中”。如果我寫的東西不在文本中,它應該告訴我“不,它不在那里。”。
可能看起來像:
<p id="p1"> Hi, how are you?</p>
<input type="text" placeholder="Type something..." id="myInput">
<button type="button" onclick="getInputValue();">Search</button>
<script>
unction getInputValue(){
let text = document.getElementById("p1");
let textElement = document.getElementById(myInput).value;
if (text.indexOf("textElement") >-1){
return true;
} else if
(text.indexOf("textElement") =-1)
return false;
console.log(myInput);
}
</script>
uj5u.com熱心網友回復:
我已經非常仔細地閱讀了您的問題,我認為以下是您的答案:
function getInputValue() {
let text = document.getElementById("p1").textContent;
let textElement = document.getElementById('myInput').value;
if (text.indexOf(textElement) !== -1){
alert("The word is in the text.");
} else if (text.indexOf(textElement) === -1) {
alert("No, it's not there.");
}
}
<p id="p1"> Hi, how are you?</p>
<input type="text" placeholder="Type something..." id="myInput">
<button type="button" onclick="getInputValue();">Search</button>
uj5u.com熱心網友回復:
方法已經很不錯了。隨函附上您修改后的 Javascript。它不區分大小寫。
function getInputValue() {
let text = document.getElementById("p1").innerHTML;
let textElement = document.getElementById('myInput').value;
if (text.toLowerCase().indexOf(textElement.toLowerCase()) !== -1){
alert("word found.");
} else if (text.indexOf(textElement.toLowerCase()) === -1) {
alert("nothing founded");
}
console.log(myInput);
}
<p id="p1"> Hi, how are you?</p>
<input type="text" placeholder="Type something..." id="myInput">
<button type="button" onclick="getInputValue()">Search</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/338712.html
標籤:javascript html
