1.JS获取json数据方法:
$.ajax();
XMLHttpRequest
fetch(a); //a代表服务器地址
实例:
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
//const prom = fetch (endpoint ); //fetch函数返回一个对象
const cities = [ ];
fetch(endpoint)
.then(respose => respose.json())
.then(data => cities.push(...data));
2.在字符串中寻找子字符串使用match函数
功能:使用正则表达式模式对字符串执行查找,并将包含查找的结果作为数组返回
函数格式:stringObj.match(rgExp) stringObj为字符串必选 rgExp为正则表达式必选项
举例:
re = /guolu/ig; // 创建正则表达式模式。 i表示不区分大小写,g表示搜索全局
r = s.match(re); // 尝试去匹配搜索字符串。
问题:如何利用match函数match变量?
const regex = new RegExp(wordsToMatch,'gi')
return city.match(regex);
3.获取搜索框输入的数据
const searchInput = document.querySelector('.search');
searchInput.addEventListener('change',displayM);
function displayM(){
console.log(this.value);
}
4.在JS中实现在<ul>下加入<li>
const suggestions = document.querySelector('.suggestions');//读取ul
suggestions.innerHTML = html;//innerHTML指代ul的每一行元素
5.从一个元素中提取子字符串高亮处理
const html = matchAarray.map(place => {
const regex = new RegExp(this.value,'gi');
const cityName = place.city.replace(regex,`<span class = "hl">${this.value}</span>`);
return `
<li>
<span class="name">${cityName},${place.state}</span>
<span class="population">${place.population}</span>
</li>
`
});
6.逗号分割数字方法
function numberWithCommas(x)
{
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g,',');
}