题解 | #选择组件#
选择组件
http://www.nowcoder.com/practice/ed0bd346dc9c4184aacda183484a3a6f
function CheckGroup(renderTo, options, isMultiple) { var that = this; that.renderTo = renderTo; that.options = options; that.isMultiple = !!isMultiple; that.initHtml(); that.initEvent(); } CheckGroup.prototype.initHtml = fInitHtml; CheckGroup.prototype.initEvent = fInitEvent; CheckGroup.prototype.toggleEl = fToggleEl; CheckGroup.prototype.isSelected = fIsSelected; CheckGroup.prototype.val = fVal; function fInitHtml() { var that = this; // 请补全代码,拼接html字符串 var sHtml = `<div class="checkgroup ${that.isMultiple ? '' : 'radius'}">` + that.options.map(option => { return `<div data-val="${option.value}" class="item">${option.text}</div>` }).join('') + '</div>' that.renderTo.innerHTML = sHtml; // 请补全代码,获取checkgroup的dom元素引用 that.el = that.renderTo.querySelector('div.checkgroup'); } function fInitEvent() { var that = this; that.el && that.el.addEventListener('click', function (event) { var item = event.target; item.classList.contains('item') && that.toggleEl(item); }); } function fToggleEl(item) { // 根据当前是单选还是多选,以及当前元素是否选中,高亮/取消���亮指定的选项dom元素 var that = this; if (that.isSelected(item)) { // 请补全代码 item.classList.remove('selected') } else if (that.isMultiple) { // 请补全代码 item.classList.add('selected') } else { // 请补全代码 item.parentNode.children.forEach(ele => { ele.classList.remove('selected') }) item.classList.add('selected') } } function fIsSelected(item) { // 请补全代码,判断item是否选中 return item.classList.contains('selected') } function fVal(values) { var that = this; if (arguments.length === 0) { // 请补全代码,获取高亮的选项元素 var items = that.el.querySelectorAll(`div.selected`); // 请补全代码,获取高亮的选项元素的data-val var result = Array.from(items).map(ele => { return ele.dataset.val }); return result; } !that.isMultiple && values.length > 1 && (values.length = 1); // 请补全代码,获取所有的选项元素 var items = that.el.querySelectorAll('.item'); // 请补全代码,在指定元素上加上高亮的class Array.from(items).forEach(ele => { // 浏览器 不支持 nodelist的 forEach 导致通不过........!!!!!!!! // (items).forEach(ele => { if(values.includes(ele.getAttribute('data-val'))) { ele.classList.add('selected') } else { ele.classList.remove('selected') } }) }z 真的让人感觉有点无语 可能跑测试用例的机子 不支持 nodelist的foreach https://developer.mozilla.org/zh-CN/docs/Web/API/NodeList
nodelist的 forEach 导致通不过........!!!!!!!!
浏览器 不支持 nodelist的 forEach 导致通不过........!!!!!!!!