不要我的点击 当我使用它进行搜索时一直返回 false



我正在使用array-include方法对数组中的项进行有意的搜索,但当我单击按钮时,它总是返回false,即使它们在那里。

var arr = ["steve", "salewa", "Morris"]
var input = document.getElementById("mysearch")
var button = document.getElementById("but1")
but1.addEventListener("click", clicked)
function clicked() {
var output = arr.includes("input.value")
console.log(output)
}
<h1>search</h1>
<input type="search" id="mysearch" name="q" placeholder="...search">
<button id="but1">check</button>

您应该使用filter()来筛选出符合指定条件的数组值。您希望在数组的每个元素(=每个名称)上使用includes(),而不是在数组本身上使用,因为当插入整个名称时,数组上的includes()只返回truefalseincludes()在数组上的工作方式与在字符串上的工作方法略有不同。您希望返回名称包含您在输入字段中输入内容的结果。

此外,您还需要使用input.value从输入中获取值。如果用"将其括起来,则将使用字符串"input.value",而不是您输入的内容。

var arr = ["steve", "salewa", "Morris"]
var input = document.getElementById("mysearch")
var button = document.getElementById("but1")
but1.addEventListener("click", clicked)
function clicked() {
var output = arr.filter(name => name.includes(input.value))
console.log(output)
}
<h1>search</h1>
<input type="search" id="mysearch" name="q" placeholder="...search">
<button id="but1">check</button>

相关内容

最新更新