-1
我想总结一些JavaScript函数。例如:总结js中的函数
document.getElementByClassName("lamp")[0]; == selector(".lamp")[0];
在这个例子中我没有问题,我的问题是下面的代码:
selector(".lamp")[0].selector(".school")[1].style.color = "red";
当我运行这段代码控制台说:
Uncaught TypeError: selector(...)[0].selector is not a function(…)
这是我的选择功能:
function selector(string){
switch (string[0]) {
case '#':
string = string.replace('#','');
return document.getElementById(string);
break;
case '.':
string = string.replace('.','');
return document.getElementsByClassName(string);
break;
case '<':
string = string.replace('<','');
return document.getElementsByTagName(string);
break;
case '?':
string = string.replace('?','');
return document.getElementsByName(string);
break;
default:
console.log('i cant select it --by selector.js--');
}
}
我该怎么办?
为什么不使用选择库像[SizzleJS](https://sizzlejs.com /)? –
你的'selector'已经是浏览器中的内建函数,它被称为'querySelector' – georg
你的函数返回类似于NodeList或Element的东西,这些类没有“selector”方法。这就是为什么链接不起作用。所以你应该返回一个有“选择器”成员的东西。 (你可以使用原型机制,但我不建议这样做。) – bert