HTML:
<div id="wrapper">
<input type="text" id="searchText">
<ul id="list-wrapper">
</ul>
</div>
CSS:
*{
margin: 0;
padding: 0;
}
#wrapper{
width: 16%;
margin: 30px auto;
}
em{
color: red;
font-style: normal;
}
#list-wrapper li{
display: flex;
justify-content: space-between;
line-height: 2;
}
JS:
const listData = [
{
name:'小芝麻饼干',
des:'色香味俱全',
createTime:'2023-02-16'
},
{
name:'南瓜饼',
des:'软糯香甜',
createTime:'2023-02-17'
},
{
name:'南瓜饼干',
des:'南瓜派甜香酥脆',
createTime:'2023-02-18'
}
]
function searchKeyword(keyword) {
const Reg = new RegExp(keyword, 'g');
$("#list-wrapper").html("");
let liEle = '';
listData.forEach(item =>{
liEle += `<li>
<p>${item.name.replace(Reg, `<em>${keyword}</em>`)}</p>
<p>${item.des.replace(Reg, `<em>${keyword}</em>`)}</p>
<p>${item.createTime}</p>
</li>`
})
$("#list-wrapper").html(liEle)
}
function searchRender(){
const iptcontent = $("#searchText").val().trim();
if(iptcontent.length > 0){
searchKeyword(iptcontent);
}
}
$('#searchText').keypress(function (even) {
if (even.keyCode == 13) {
searchRender()
}
})