经过几次硬编码递归getElementsByClassName方法的尝试后,我解决了以下问题:
var getElementsByClassName = function(className) {
var result = [];
function inspect(element) {
var children = element.children;
for(var i = 0; i < children.length; i++) {
if(children[i].classList.contains(className)) {
result.push(children[i]);
}
if(children[i].hasChildNodes) {
inspect(children[i]);
}
}
}
inspect(document);
return result;
};
但是,我无法理解为什么这个解决方案不起作用,考虑到className返回我们可以测试的值:
var getElementsByClassName = function(className) {
var result = [];
function inspect(element) {
if (element.className === className) result.push(element);
var children = element.children;
for(var i = 0; i < children.length; i++) {
inspect(children[i]);
}
}
inspect(document);
return result;
};
感谢您提前获得的帮助,如果您有任何其他改进我的代码的建议,请告知我们。
答案 0 :(得分:1)
这是一种使用你的算法的解决方案,但是有更好的方法可以实现,你也可以在没有内部函数的情况下实现。
Canvas