js06 - Type Ahead

内容

#涵括特性:
	- Promise
		fetch()//接受资源路径,返回一个promise对象
		then()
		json()//使用json读取response中的数据
	- Array
		filter()
		map()
		push()//arr1.push(...arr2)
		join()
		Spread syntax 拓展语句//利用拓展简化push语句
	- RegExp
		match()
		replace()
	//定义json文件地址
  const endpoint = 'https://gist.githubusercontent.com/soyaine/81399bb2b24ca1bb5313e1985533c640/raw/bdf7df2cbcf70706c4a5e51a7dfb8c933ed78878/TangPoetry.json';
	//定义poetrys数组
  const poetrys = [];
  fetch(endpoint)//获取Http响应
    .then(blob => blob.json())//获取图片
    .then(data => poetrys.push(...data))//获取相关data
  //定义方法				相关字眼		诗词array
  function findMatches(wordToMatch,poetrys){
  	//使用关键词过滤器
    return poetrys.filter(poet =>{
    	//此处gi分别为可匹配多个关键词组及不区分大小写
      const regex = new RegExp(wordToMatch,'gi');
      //定义作者
      const author = poet.detail_author.join('')
      //返回相关匹配信息
      return poet.detail_text.match(regex)||poet.title.match(regex)||author.match(regex)
    })
  }
	//定义方法
  function displayMatches(){
    const matches = findMatches(this.value,poetrys);
    const regex = new RegExp(this.value,'gi');
    const html = matches.map(poet=>{
      const text = poet.detail_text.replace(regex,`<span class="hl">${this.value}</span>`)
      const title = poet.title.replace(regex,`<span class="hl">${this.value}</span>`)
      return `
      <li>
        <span class="poet">${text}</span>
        <span class="title">${title} - ${poet.detail_author[0]}</span>
      </li>
      `
    }).join('');
    suggestions.innerHTML = html;
  }
  const search = document.querySelector('.search');
  const suggestions = document.querySelector('.suggestions');

  search.addEventListener('change',displayMatches);
  search.addEventListener('keyup',displayMatches)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值