题解 | #选择组件#
选择组件
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 = ''; var sHtmlInner = ''; var options = this.options; for(let item of options){ sHtmlInner+=`<div data-val="${item.value}" class="item">${item.text}</div>` } sHtml = `<div class="checkgroup radius">${sHtmlInner}</div>`; that.renderTo.innerHTML = sHtml; // 请补全代码,获取checkgroup的dom元素引用 that.el = that.renderTo; } function fInitEvent() { var that = this; that.el && that.el.addEventListener('click', function (event) { var item = event.target; console.log(item); item.classList.contains('item') && that.toggleEl(item); }); } function fToggleEl(item) { // 根据当前是单选还是多选,以及当前元素是否选中,高亮/取消���亮指定的选项dom元素 var that = this; const value = item.dataset.val; var optionsDom = document.querySelectorAll('.checkgroup .item'); if (that.isSelected(item)) { // 请补全代码 item.classList.remove('selected'); } else if (that.isMultiple) { // 请补全代码 for(var i=0;i<optionsDom.length;i++){ var item = optionsDom[i]; if (item.dataset.val === value){ item.classList.add('selected'); } } } else { // 请补全代码 for(var i=0;i<optionsDom.length;i++){ var item = optionsDom[i]; if (item.dataset.val === value){ item.classList.add('selected'); } else { item.classList.remove('selected'); } } } } function fIsSelected(item) { // 请补全代码,判断item是否选中 return item.classList.contains('selected'); } function fVal(values) { var that = this; if (arguments.length === 0) { // 请补全代码,获取高亮的选项元素 var items = document.querySelectorAll('.checkgroup .selected'); // 请补全代码,获取高亮的选项元素的data-val var result = Array.from(items).map(item => item.dataset.val); return result; } !that.isMultiple && values.length > 1 && (values.length = 1); // 请补全代码,获取所有的选项元素 var items = document.querySelectorAll('.checkgroup .item'); // 请补全代码,在指定元素上加上高亮的class for(var i=0;i<values.length;i++){ var value = values[i]; for(var j=0;j<items.length;j++){ var item = items[j]; if (item.dataset.val === value){ item.classList.add('selected'); } else { if (!that.isMultiple){ item.classList.remove('selected'); } } } } }