城市小案例的js原生代码

function City(opts) { this.opts = opts; this.info = document.querySelector(this.opts.info); this.list = document.querySelector(this.opts.list); this.bindEvent(); this.bindClick(); } City.prototype = { constructor: City, bindEvent: function() { var arr = Object.keys(this.opts.data); //分解开的字母 var temp = []; for (var i = 1; i < arr.length; i += 4) { temp.push(arr.slice(i, i + 4)); } //标题追加页面 var str = '
  • 热门
  • '; temp.forEach(function(item) { str += `
  • ${item.join('')}
  • `; }) this.list.innerHTML = str; //加样式 this.lis = this.list.querySelectorAll('li'); this.lis[0].className = 'bg'; this.hotCity(); }, hotCity: function() { //默认热门内容 var str = hotel_hotData["热门"]; var reg = /[\u4e00-\u9fa5]{2,}/g; var arr = str.match(reg); var newStr = '

    热门

    '; arr.forEach(function(con) { newStr += ` ${con}`; }) this.info.innerHTML = newStr; }, bindClick: function() { var that = this; //点击标题时 this.lis = Array.from(this.list.querySelectorAll('li')); this.lis.forEach(function(item) { item.onclick = function() { that.hideAll(); item.className = 'bg'; if (item.innerHTML == "热门") { //默认 that.hotCity(); } else { //渲染每个内容 var val = item.innerHTML; var arr = val.split(''); var str = ''; arr.forEach(function(item) { str += `

    ${item}

    `; var reg = /[\u4e00-\u9fa5]{2,}/g; var temp = hotel_hotData[item].match(reg); temp.forEach(function(c) { str += ` ${c}`; }) }) that.info.innerHTML = str; } } }) }, hideAll: function() { this.lis.forEach(function(item) { item.className = ""; }) } } new City({ list: '.list', info: '.info', data: hotel_hotData })

    猜你喜欢

    转载自www.cnblogs.com/mapsxy/p/9229483.html