发布于 2017-06-24 23:47:33 | 123 次阅读 | 评论: 0 | 来源: 网友投递
这里有新鲜出炉的Javascript教程,程序狗速度看过来!
JavaScript客户端脚本语言
Javascript 是一种由Netscape的LiveScript发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
function test() {
var result;
result = find('i', 'g');
result.id !== 'c' && alert('fail (i, g)');
result = find('g', 'h');
result.id !== 'a' && alert('fail (g, h)');
result = find('d', 'e');
result.nodeName.toLowerCase() !== 'html' && alert('fail (d, e)');
result = find('c', 'b');
result.nodeName.toLowerCase() !== 'html' && alert('fail (c, b)');
}
function find() {
var length = arguments.length,
i = 0,
node, //当前节点
parent, //父节点
counter = 0,
uuid, //给DOM的唯一标识符
hash = {}; //最后结果的map
//对每一个元素,向上遍历至document
//这个双层的循环是不可避免的
for (; i < length; i++) {
//获取node
node = arguments[i];
if (typeof node == 'string') {
node = document.getElementById(node);
}
//向上遍历
while (parent = node.parentElement || node.parentNode) {
//到document就停下来,不然就是死循环
if (parent.nodeType == 9) {
break;
}
//获取或添加一下标识符
uuid = parent.getAttribute('data-find');
if (!uuid) {
uuid = '_' + (++counter); //避免chrome对hash重排序
parent.setAttribute('data-find', uuid);
}
//增加计数
if (hash[uuid]) {
hash[uuid].count++;
}
else {
hash[uuid] = {node: parent, count: 1};
}
node = parent;
}
}
//hash中只存有各节点向上遍历经过的父节点,不应该很大
//因此这个循环是比较快的
for (i in hash) {
if (hash[i].count == length) {
return hash[i].node;
}
}
};