就像在jQuery中我们可以使用$(".classname"),javascript中也有类似的东西吗?或者,如果我们没有这样的方法,那么我该如何实现呢.
根据http://www.dustindiaz.com/getelementsbyclass/, 我将遍历所有标签,然后收集所有与指定类相同的元素.
有没有更好的解决方案?
bob*_*nce 14
我将不得不遍历所有标签,然后收集所有与指定类相同的元素.
是.但是,有几种方法可以改善您链接的页面的功能:
传入RegExp-escape类名,以便它不会被类名中的标点符号破坏.例如,呼叫不getElementsByClassName('ab.cd')应该匹配class="abxcd".
定义的HTML5规范getElementsByClassName允许多个以空格分隔的类名,所有这些都必须存在于要匹配的元素上.实现这一点.
可选地,允许传入标记名称的提示以缩小函数必须查看的元素的数量,以用于仅影响一种类型标记的常见情况.(这对于真正的浏览器本机getElementsByClassName调用没有任何作用,所以你不应该依赖它来过滤掉你不想要的元素.)
示例实现:
if (!('getElementsByClassName' in document)) {
document.getElementsByClassName= function(classnames, taghint) {
var exps= classnames.split(/\s+/).map(function(name) {
name= name.replace(/([/\\^$*+?.()|[\]{}])/g, '\\$1');
return new RegExp('(^|\\s)'+name+'(\\s|$)');
});
var els= this.getElementsByTagName(taghint || '*');
var matches= [];
for (var i= 0, n= this.length; i<n; i++)
var el= els[i];
if (exps.every(function(exp) {
return exp.test(el.className);
}))
matches.push(el);
}
return matches;
};
}
Run Code Online (Sandbox Code Playgroud)
然而,这也使用了IE还没有的一些ECMAScript第五版(或JavaScript 1.6)数组方法,因此您还必须为这些方法添加回退实现:
if (!('map' in Array.prototype)) {
Array.prototype.map= function(mapper, that) {
var other= new Array(this.length);
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
other[i]= mapper.call(that, this[i], i, this);
return other;
};
}
if (!('every' in Array.prototype)) {
Array.prototype.every= function(tester, that) {
for (var i= 0, n= this.length; i<n; i++)
if (i in this && !tester.call(that, this[i], i, this))
return false;
return true;
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7016 次 |
| 最近记录: |