我有這個代碼來搜索我的 JSON 資料,但想要當我搜索時,我得到一個彈出視窗,說明它是否存在于我的 json 檔案中。有大佬可以分析一下嗎?我基本上需要一個 HTML 搜索框來搜索相應的 JSON 資料并在彈出視窗中回傳結果
var data = [
{
"id":198,
"name":"Aaron Garo",
},
{
"id":345,
"name":"Michael Stines",
},
{
"id":545,
"name":"Ully Heiz",
},
{
"id":678,
"name":"Asgaf Torino",
}
]
output = "";
$.each(data, function(key, val){
output = "<div class='values'>";
output = '<h5 >' val.id '</h5>';
output = '<p >' val.name '</p>'
output = "</div>";
});
$('#content').html(output);
/* SEEKER FUNCTION */
if (!RegExp.escape) {
RegExp.escape = function (s) {
return s.replace(/[-[]{}()* ?.,\^$|#s]/g, "\$&")
};
}
jQuery(function(){
var $rows = $('.values');
$('#seeker').keyup(function () {
var regex = new RegExp(RegExp.escape($.trim(this.value).replace(/s /g, ' ')), 'i')
$rows.hide().filter(function () {
var text = $(this).children(".value-name").text().replace(/s /g, ' ');
return regex.test(text)
}).show();
});
});
.values{
background: #FFFFAA;
}
.search-bar{
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="search-bar">
<input type="text" id="seeker">
</div>
<div id="content"></div>
uj5u.com熱心網友回復:
你的意思是這樣?
var data = [{ "id":198, "name":"Aaron Garo" },{ "id":345, "name":"Michael Stines" },{ "id":545, "name":"Ully Heiz" },{ "id":678, "name":"Asgaf Torino"}];
$('#content').html(data.map(({id,name}) => `<div class='values'><h5 >${id}</h5><p >${name}</p></div>`));
/* SEEKER FUNCTION */
if (!RegExp.escape) RegExp.escape = s => s.replace(/[-[]{}()* ?.,\^$|#s]/g, "\$&");
$(function(){
var $rows = $('.values');
$('#seeker').keyup(function () {
var regex = new RegExp(RegExp.escape($.trim(this.value).replace(/s /g, ' ')), 'i')
$rows.hide().filter(function () {
var text = $(this).children(".value-name").text().replace(/s /g, ' ');
return regex.test(text)
}).show();
const count = $(":visible",$rows).length;
$("#res").text(count/2 " found").toggle(count > 0)
});
});
.values{
background: #FFFFAA;
}
.search-bar{
width: 100%;
}
#res { display: none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="search-bar">
<input type="text" id="seeker"> <span id="res"></span>
</div>
<div id="content"></div>
uj5u.com熱心網友回復:
Solution
Presisely what you need
var data = [{
"id": 198,
"name": "Aaron Garo",
},
{
"id": 345,
"name": "Michael Stines",
},
{
"id": 545,
"name": "Ully Heiz",
},
{
"id": 678,
"name": "Asgaf Torino",
}
]
output = "";
$.each(data, function(key, val) {
output = `<option value="Name : ${val.name}; ID : ${val.id}" />`
});
$('#names').html(output);
/* SEEKER FUNCTION */
if (!RegExp.escape) {
RegExp.escape = function(s) {
return s.replace(/[-[]{}()* ?.,\^$|#s]/g, "\$&")
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="search-bar">
<input type="text" id="seeker" list="names">
<datalist id="names">
</datalist>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334314.html
標籤:
