【问题标题】:summarize functions in js总结js中的函数
【发布时间】:2017-05-24 15:33:42
【问题描述】:

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

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这样的选择器库?
  • 你的selector已经是浏览器内置的,叫做querySelector
  • 您的函数返回类似 NodeList 或 Element 的内容,这些类没有“选择器”方法。这就是链接不起作用的原因。因此,您应该返回具有“选择器”成员的内容。 (你可以使用原型机制,但我不建议这样做。)
  • 以这样的方式开始(对于 id 案例): case '#': string = string.replace('#',''); return (function(elem) { return {selector: function(string) { /* 用 elem / }, dom: elem / 原始元素 */ }; })(document.getElementById(细绳));休息;

标签: javascript function summarize


【解决方案1】:

你应该使用原型:

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

这段代码运行正常,没有任何错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多