簡體   English   中英

使用 javascript 方法搜索關鍵字 search();

[英]Searching for keywords with javascript method search();

我有這個程序,用戶可以在其中輸入文本,然后單擊一個按鈕,在用戶輸入的關鍵字中搜索關鍵字,如果找到一個關鍵字,則提示找到:但如果沒有工作,則提示:未找到! 我試過這樣的事情:

  function myFunction() {
  var str = document.getElementById('demo'); 
  var n = str.search("wow");

  if (n = true){
      alert("found");
  } else {
      alert("not found");
  }

但這沒有用。 每當我搜索某些東西時,它都會給我這個:str.search 不是 function。

這是我的完整代碼:

 function myFunction() { var str = document.getElementById('demo'); var n = str.search("wow"); if (n = true){ alert("found"); } else { alert("not found"); } }
 <input type="text" id="demo"/> <button onclick="myFunction()">Search</button>

str實際上不是字符串,它是HTML element

var str = document.getElementById('demo'); 

如果你想使用str.search你必須使用正則表達式,我建議使用內置的 function includes這種功能

  1. 您要檢查輸入的value ,而不是輸入本身。
  2. 最好在此處使用includes而不是search
  3. =是賦值; =====用於比較。 此外,比較 boolean 值幾乎總是多余的。

 function myFunction() { var str = document.getElementById('demo').value; var n = str.includes("wow"); if (n) { alert("found"); } else { alert("not found"); } }
 <input type="text" id="demo" /> <button onclick="myFunction()">Search</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM