我尝试了一个自定义的 getElementById() 方法来从 HTML 页面中检索 DOM 元素。这是定义。
document.customGetElById = function(passedId){
var nodeFound = null;
recursive = function(nodes)
{
for(var i =0 ; i< nodes.length; i++)
{
if(nodes[i].nodeType == 1) //element nodes
{
//console.log(nodes[i].id); //only element nodes have id's
if(nodes[i].id == passedId)
{
//console.log(nodes[i]);
nodeFound = nodes[i];
return;
}
if(nodes[i].childNodes)
{
//console.log('there are child nodes inside it');
recursive(nodes[i].childNodes);
}
}
}
}
recursive(document.body.childNodes);
return nodeFound;
};
这是正确的做法吗?这对性能有好处吗? 它与覆盖 native getElementById() 方法无关。 native函数是怎么写的?有人可以帮帮我吗? 提前致谢。
最佳答案
原生函数不是用 JS 编写的,因此任何 JS 方法都必然与原始的 getElementById
不同。
您的函数也可能比浏览器的实现效率低,因为您所做的只是从大量其他 native 函数中复制它。
关于javascript - 自定义 javascript document.getElementById() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13620603/