一道名为"敲门砖"的面试题:
用面向对象的方法写,点击列表内,子元素的子标签, 来删除子元素
敲门砖
考点:
- 递归(删除标签, 需要找到列表的直属子标签, 需要通过递归层层往上找,
parentNode
)- 冒泡(只需为顶级父元素addEventListener绑定事件, 并通过e.target区分子标签, 即可实现一次绑定, 多次使用)
- ES6语法(使用ES6的class 构造方法需要指明constructor函数)
- 布局(使用网格布局,快速实现内联元素的两端对齐, justify-content: span-between)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>阿里敲门砖</title>
<style>
li{
list-style: none;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #fdf6e3;
border: 1px solid #0c8ac5;
height: 100px;
padding: 5px;
}
.del{
border:1px solid #323232;
color: #c03035;
}
</style>
</head>
<body>
<ol class="list">
<li><span class="desc">黄河之水</span><span class="del">X</span></li>
<li><span class="desc">天上来</span><span class="del">X</span></li>
<li><span class="desc">奔流</span><span class="del">X</span></li>
<li><span class="desc">到海</span><span class="del">X</span></li>
<li><span class="desc">不复回</span><span class="del">X</span></li>
<li><span class="desc">君不见</span><span class="del">X</span></li>
<li><span class="desc">高唐明镜</span><span class="del">X</span></li>
<li><span class="desc">悲白发</span><span class="del">X</span></li>
</ol>
<ol class="list">
<li><span class="desc">到海</span><span class="del">X</span></li>
<li><span class="desc">不复回</span><span class="del">X</span></li>
<li><span class="desc">天上来</span><span class="del">X</span></li>
<li><span class="desc">奔流</span><span class="del">X</span></li>
<li><span class="desc">君不见</span><span class="del">X</span></li>
<li><span class="desc">黄河之水</span><span class="del">X</span></li>
<li><span class="desc">高唐明镜</span><span class="del">X</span></li>
<li><span class="desc">悲白发</span><span class="del">X</span></li>
</ol>
<script>
class List{
constructor(els){
// 将this转换为局部变量self, 个人爱好Python3,这个写法类似Python3
let self = this;
// 根据类选择器,选择所有符合条件的的清单, 并生成列表
let el = Array.from(document.querySelectorAll(els))
// 为每个清单绑定事件
el.forEach(item => item.addEventListener('click', function(e){
// 如果点击的元素的类名带有del, 则可以删除这条标签
if (e.target.className.indexOf('del') > -1){
// 移除相应的子元素
self.removeDom.call(self, item, e.target)
}
}))
}
removeDom(item, tg){
let self = this;
// 设置移除判定函数
let judgeRemoveDom = function(item, tg){
// 获取触发事件元素的父级元素
let parentNode = tg.parentNode;
// 如果当前找到的元素的父元素恰好为item, 则可以直接移除
if (item === parentNode){
item.removeChild(tg);
}
// 如果当前的父元素不是item, 则继续往上找
else{
tg = parentNode;
judgeRemoveDom(item, tg);
}
}
judgeRemoveDom(item, tg);
}
}
window.addEventListener('DOMContentLoaded', function(){
new List('.list')
})
</script>
</body>
</html>
网友评论