datalist案例地址:https://www.runoob.com/try/try.php?filename=tryjsref_datalist_options
标签被用来在为 元素提供"自动完成"的特性。用户能看到一个下拉列表,里边的选项是预先定义好的,将作为用户的输入数据
let input = document.getElementById('searchName');
let input2 = document.getElementById('searchName2');
let input3 = document.getElementById('searchName3');
watchIpt(input,(v)=>{
if(v.trim().length === 0){
$('#browsers').html('');
}else{
searchIpt(v)
}
})
function watchIpt(elem,callback){
let notChinese = true;
elem.addEventListener('compositionstart',(e)=>{
console.log('start');
notChinese = false;
})
elem.addEventListener('compositionend',(e)=>{
console.log('end');
notChinese = true;
})
elem.addEventListener('input',(e)=>{
setTimeout(()=>{
if(notChinese){
callback(e.target.value)
}
})
})
}
function searchIpt(iptVal){
const list = [
{
name:'苹果1'
},
{
name:'苹果2'
},
{
name:'梨树'
},
{
name:'苹果苹果苹果苹果苹果树'
},
{
name:'苹果1'
},
{
name:'苹果2'
},
{
name:'梨树'
},
{
name:'苹果苹果苹果苹果苹果树'
},
{
name:'苹果1'
},
{
name:'苹果2'
},
{
name:'梨树'
},
{
name:'苹果苹果苹果苹果苹果树'
},
{
name:'苹果1'
},
{
name:'苹果2'
},
{
name:'梨树'
},
{
name:'苹果苹果苹果苹果苹果树'
},
{
name:'苹果1'
},
{
name:'苹果2'
},
{
name:'梨树'
},
{
name:'苹果苹果苹果苹果苹果树'
},
{
name:'苹果1'
},
{
name:'苹果2'
},
{
name:'梨树'
},
{
name:'苹果苹果苹果苹果苹果树'
},
{
name:'苹果1'
},
{
name:'苹果2'
},
{
name:'梨树'
},
{
name:'苹果苹果苹果苹果苹果树'
},
{
name:'葡萄树'
},
];
$('#browsers').html('');
let optEle = ''
list.forEach(item =>{
optEle += `<option value="${item.name}">`
})
$('#browsers').append(optEle);
}