检查输入是否等于 div 中的文本
Check to see if input is equal to text inside div
我正在尝试构建一个搜索框来在我的站点中搜索文本。现在我正在尝试创建一个 jquery keyup() 函数,它从我的搜索框中获取输入并将其与两个 div 中的文本进行比较。当我在搜索输入中键入 div 的文本内容 Tom 或 Randy 时,这段代码似乎没有按我预期的方式工作。结果是 console.log("nothing").
我的Html
<input type="text" id="searchfor">
<div class ="name"> Tom </div>
<div class ="name"> Randy </div>
我的jquery
$(document).ready(function(){
$('#searchfor').keyup(function(){
$(".name").each(function(){
var $divText = $(".name").text().trim().toLowerCase();
var $searchInput = $("#searchfor").val().trim().toLowerCase();
if($searchInput === $divText) {
console.log("something");
}else{
console.log("nothing");
}
});
});
});
我想知道如何让 $searchInput 等于 $divText,这样当有人在搜索输入字段中输入 Randy 时,该函数将 console.log("something") .谢谢
问题是 var $divText = $(".name").text();
将合并所有元素集合的文本。
在你的 each
中你想要特定的实例所以使用 $(this)
.
$('#searchfor').keyup(function() {
// no need to get value in each iteration of loop...just store it here once
var $searchInput = $(this).val().trim().toLowerCase();
// within loop `this` is instance of div.name
$(".name").each(function() {
var $divText = $(this).text().trim().toLowerCase();
if ($searchInput === $divText) {
console.log("something");
} else {
console.log("nothing");
}
});
});
只有输入全名才会匹配。
如果您只想部分匹配,请使用 indexOf()
我正在尝试构建一个搜索框来在我的站点中搜索文本。现在我正在尝试创建一个 jquery keyup() 函数,它从我的搜索框中获取输入并将其与两个 div 中的文本进行比较。当我在搜索输入中键入 div 的文本内容 Tom 或 Randy 时,这段代码似乎没有按我预期的方式工作。结果是 console.log("nothing").
我的Html
<input type="text" id="searchfor">
<div class ="name"> Tom </div>
<div class ="name"> Randy </div>
我的jquery
$(document).ready(function(){
$('#searchfor').keyup(function(){
$(".name").each(function(){
var $divText = $(".name").text().trim().toLowerCase();
var $searchInput = $("#searchfor").val().trim().toLowerCase();
if($searchInput === $divText) {
console.log("something");
}else{
console.log("nothing");
}
});
});
});
我想知道如何让 $searchInput 等于 $divText,这样当有人在搜索输入字段中输入 Randy 时,该函数将 console.log("something") .谢谢
问题是 var $divText = $(".name").text();
将合并所有元素集合的文本。
在你的 each
中你想要特定的实例所以使用 $(this)
.
$('#searchfor').keyup(function() {
// no need to get value in each iteration of loop...just store it here once
var $searchInput = $(this).val().trim().toLowerCase();
// within loop `this` is instance of div.name
$(".name").each(function() {
var $divText = $(this).text().trim().toLowerCase();
if ($searchInput === $divText) {
console.log("something");
} else {
console.log("nothing");
}
});
});
只有输入全名才会匹配。
如果您只想部分匹配,请使用 indexOf()