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

阿里巴巴:实现一些主流框架的循环渲染(笔试) #27

Open
foreverzmy opened this issue May 1, 2019 · 1 comment
Open

Comments

@foreverzmy
Copy link

foreverzmy commented May 1, 2019

面试公司:

阿里巴巴

面试环节:

笔试

问题:

var items = [
  { name: 'item1' },
  { name: 'item2' }
];
var str = '<div ali-for="item in items">{{item.name}}<div>';

// 对应生成的dom  
ParseDom(str);
// <div>item1</div>  
// <div>item2</div>  
@foreverzmy foreverzmy changed the title To focus7eleven:实现一些主流框架的循环渲染 To focus7eleven:实现一些主流框架的循环渲染(阿里巴巴) May 1, 2019
@acodercc acodercc changed the title To focus7eleven:实现一些主流框架的循环渲染(阿里巴巴) 阿里巴巴:实现一些主流框架的循环渲染(笔试) May 6, 2019
@lhyt
Copy link

lhyt commented Jun 11, 2019

支持其他标签、多个节点、属性

var items = [
  { name: 'item1' },
  { name: 'item2' }
];

// ***********
const s = {}
s.items = items
function ParseDom(str) {
	// 借助dom子节点使用dom方法
	const mid = document.createElement('div')
	mid.innerHTML = str
	const { children } = mid
	let res = ''
	// 遍历子节点
	;[...children].forEach(c => {
		// 找属性节点
		const attrs = [...c.attributes]
		const targetAttr = attrs.find(x => x.name === 'ali-for');
		const nodename = c.nodeName.toLocaleLowerCase();
		// 属性全部写进去
		const attrsStr = attrs.reduce((r, c) => {
			if (c.name !== 'ali-for') {
				r += ` ${c.name}="${c.value}"`
			}
			return r
		}, '')
		if (!targetAttr) {
			// 没有循环渲染标记
			res += `<${nodename}${attrsStr}>${c.innerHTML}</${nodename}>`
			return
		}
		// 循环渲染
		const vfor = targetAttr.nodeValue
		const o = vfor.split(' in ')[1]
		const k = c.innerText.match(/\{\{(.*)\}\}/)[1].split('.')[1]
		;s[o].forEach(x => {
			res += `<${nodename}${attrsStr}>${x[k]}</${nodename}>`
		})
	})
	return res
}
// ***********

var str = '<div ali-for="item in items">{{item.name}}</div>';
// 对应生成的dom  
ParseDom(str);

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

4 participants