在 html 中创建一个搜索栏,将搜索输入存储为字符串

问题描述 投票:0回答:1
javascript html
1个回答
0
投票

你错过了几件事。
首先,您需要解析您的

b
字符串,以创建字符串数组
["Apple", "Banana"]

其次,您尝试对 HTML 输入值调用
innerHTML()
函数,但您不能这样做。
第三,当输入字符串与您的数据字符串匹配时,您必须从函数返回以停止
for
循环。

function test(){
    var a = document.getElementById('search').value;
    var b = "Apple, Banana";
    var ar = b.split(", "); // arrray of strings ["Apple", "Banana"]

    for (var c = 0; c <= 1; c++) {
      if (a.match(ar[c])){ // no innerHTML function
        document.getElementById('show').innerHTML = "You search " + "'" + ar[c] + "'";
        return; // return after match
      } else 
        document.getElementById('show').innerHTML = "ERROR.";            
    }
}
<i id="show"></i>//Output will show here//

<input id="search" type="text" placeholder="Search...">//Search Bar//
<button value="submit" onclick="return test()" type="submit">Search</button>

© www.soinside.com 2019 - 2024. All rights reserved.