总结js中的函数

时间:2017-01-10 07:59:14

标签: javascript function summarize

我想总结一些JavaScript函数。例如:

document.getElementByClassName("lamp")[0]; == selector(".lamp")[0];

在这个例子中我没有问题,我的问题是以下代码:

selector(".lamp")[0].selector(".school")[1].style.color = "red";

当我运行此代码控制台时说:

  

Uncaught TypeError:selector(...)[0] .selector不是函数(...)

这是我的选择器功能:

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--');
  }
}

我该怎么办?

1 个答案:

答案 0 :(得分:0)

你应该使用原型:

&#13;
&#13;
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--');
  }
}
Object.prototype.selector = function(){
  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--');
  }
};
&#13;
&#13;
&#13;

此代码正确运行,没有任何错误