漂亮的东西与普通的JavaScript将能够使用forEach,map,filter等,在项目返回的document.querySelectorAll,document.getElementsBy*等等.
这样可以减少对jQuery的依赖,并简化代码.现在,这就是我们如何以丑陋的方式做到这一点:
[].forEach.call( document.querySelectorAll(sel), function(el) {
});
Run Code Online (Sandbox Code Playgroud)
这是......详细.
任何方式能够立即使用forEach和喜欢的元素返回?
Flo*_*ine 14
如果您在Chrome上进行测试,那么天真的方法就是:
NodeList.prototype.forEach = Array.prototype.forEach;
Run Code Online (Sandbox Code Playgroud)
这有效.在Webkit上.但它不适用于Firefox.因为FF返回HTMLCollection ...
我找到的最跨浏览器的方式:
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
Run Code Online (Sandbox Code Playgroud)
它不适用于IE8及更低版本,因为它们在向宿主对象原型添加属性时会窒息.
完整清单:
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.map = HTMLCollection.prototype.map = Array.prototype.map;
NodeList.prototype.filter = HTMLCollection.prototype.filter = Array.prototype.filter;
NodeList.prototype.reduce = HTMLCollection.prototype.reduce = Array.prototype.reduce;
NodeList.prototype.reduceRight = HTMLCollection.prototype.reduceRight = Array.prototype.reduceRight;
NodeList.prototype.every = HTMLCollection.prototype.every = Array.prototype.every;
NodeList.prototype.some = HTMLCollection.prototype.some = Array.prototype.some;
Run Code Online (Sandbox Code Playgroud)
或者,请我们亲爱的BERGI(也因为它是清洁剂):
['forEach', 'map', 'filter', 'reduce', 'reduceRight', 'every', 'some'].forEach(
function(p) {
NodeList.prototype[p] = HTMLCollection.prototype[p] = Array.prototype[p];
});
Run Code Online (Sandbox Code Playgroud)
考虑到与完美技能的联系,它在那里几乎无关紧要.问题是DOM在扩展时在浏览器上的行为大多不一样.除了IE <= 8之外,所有浏览器中的修改都是合理的.
function forEach( a, fn ) {
return [].forEach.call(a, fn);
};
forEach(document.querySelectorAll(sel), function(el) {
});
Run Code Online (Sandbox Code Playgroud)
还有很多:
function map( a, fn ) {
return [].map.call(a, fn);
};
function filter( a, fn ) {
return [].filter.call(a, fn);
};
function reduce( a, fn ) {
return [].reduce.call(a, fn);
};
function reduceRight( a, fn ) {
return [].reduceRight.call(a, fn);
};
function every( a, fn ) {
return [].every.call(a, fn);
};
function some( a, fn ) {
return [].some.call(a, fn);
};
Run Code Online (Sandbox Code Playgroud)
也许你需要
[].slice.call(a)
Run Code Online (Sandbox Code Playgroud)
在某些情况下.
function forEach(a, fn) {
return [].forEach.call([].slice.call(a), fn);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5330 次 |
| 最近记录: |