元素创建的快捷方式,基于MooTools »
最近一段时间总是在敲代码,为了减少输入量,得想一些方法,得解放自己。MooTools的元素创建,需要敲打很多的字母,如果把行输入,改为线输入就好了。
1 2 3 4 | var curly = new Element('div', { id : 'curly', 'class' : 'stooge' }); |
此时,不由的想起了jQuery的方法,创建HTML是很方便的,
1 | var $curly = $('<div id="curly" class="stooge"/>'); |
对我来说,这就是是快速,简单,很自然的在JavaScript中输入HTML,不过这种做法有的时候很可怕,人们会滥用此方式。有些人甚至喜欢使用双引号,然后逃脱一切的属性引用。
我喜欢MooTools的干净和简洁,今天我意识到我可以使用有限的选择来创建一个元素。我喜欢这个非常好的想法。
1 | var curly = $E('div#curly.stooge'); |
更新:update: Apparently I’m not the first to think of this. A couple weeks before I wrote this post, this commit was made to MooTools 2.0 adding this capability to new Element. The idea came from Thomas Aylott. I am so happy to see this become a part of the next version of MooTools!
我们知道,$E在MooTools 1.1中是选择一个符合给出选择器的元素 ,但是在MooTools 1.2+版中,$E它是Element:getElement的别名函数,以document为元素搜索上下文,但只返回第一个元素。$ A和$ H分别是创建一个创建一个数组拷贝和一个哈希(Hash),因此很自然的就用$E来创建元素。如果你不喜欢我的推理,那么你可以更改名称和我保证我不会找你。
1 2 3 4 5 6 7 8 9 10 11 12 13 | function $E(tag, props) { if (typeof props == 'string') props = { style : props }; if (typeof tag == 'string') { var id = tag.match(/#([\w-]+)/); var classes = tag.match(/(?:\.[\w-]+)+/); tag = tag.replace(/[#.].*/, ''); props = props || {}; if (id) props.id = id[1]; if (classes) props['class'] = classes[0].replace(/\./g, ' '); } return new Element(tag || 'div', props); }; |
有了这个神奇的有效率的函数,您可以快速而轻松地创建一个可选的id和任何数目的class,以及通过第二个可选参数,您可以传递其他属性给元素。
事实上,你可以省略一个标签,它会默认为<div> 。
语法:
1 | var moe = $E('#moe.stooge.leader', {...}); |
非常感谢您使用这个新的快捷方式。
Note to plugin developers: If you decide to use this, please place it inside of a closure so it doesn’t override someone else’s $E function. I saw this suggestion on the MooTools Twitter2 so I can imagine this becoming a problem —
1 | $E = document.getElement.bind(document); |
—–THE END—–