Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

面向对象的方式删除当前点击的列表 #20

Open
yizihan opened this issue Mar 22, 2018 · 0 comments
Open

面向对象的方式删除当前点击的列表 #20

yizihan opened this issue Mar 22, 2018 · 0 comments

Comments

@yizihan
Copy link
Owner

yizihan commented Mar 22, 2018

<ul class="list">
	<li>第一行 <span class="del">X</span></li>
	<li>第二行 <span class="del">X</span></li>
	<li>第三行 <span class="del">X</span></li>
	<li>第四行 <span class="del">X</span></li>
	<li>第五行 <span class="del">X</span></li>
</ul>
<ul class="list">
	<li>第一行 <span class="del">X</span></li>
	<li>第二行 <span class="del">X</span></li>
	<li>第三行 <span class="del">X</span></li>
	<li>第四行 <span class="del">X</span></li>
	<li>第五行 <span class="del">X</span></li>
</ul>
// 使用面向对象
// 解耦事件绑定和执行
// 事件委托
class List {
	constructor (sel) {
		// 转为数组
		this.el = Array.from(document.querySelectorAll(sel));
		let self = this;	// self = List {el: Array(2)}
		this.el.forEach(item => {
			item.addEventListener('click', function(e) {
				debugger
				// 判断触发点是span
				if (e.target.className.indexOf('del') > -1) {
					// 执行删除元素方法
					self.removeItem.call(self, e.target);
				}
			})
		})
	}
	removeItem (target) {
		let self = this;	// self指向ul元素
		let findParent = function (node) {
			// 1. node = span.del
			// 2. node = li
			let parent = node.parentNode;
			// 1. parent = li
			// 2. parent = ul.list === self.el
			let root = self.el.find(item => item === parent);
			// 1. root = undefined parent = li
			// 2. root = ul.list parent = ul.list
			if (root) {
				// 2. 删除当前li元素
				root.removeChild(node);
			} else {
				// 1. 继续执行查找
				findParent(parent);
			}
		}
		findParent(target)
	}
}
window.addEventListener('DOMContentLoaded', function() {
	new List('.list')	// 实例化调用
})
@yizihan yizihan changed the title 试题 - 面向对象的方式删除当前点击的列表 面试题 Mar 22, 2018
@yizihan yizihan changed the title 面试题 面向对象的方式删除当前点击的列表 Aug 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant