【问题标题】:Rebuild jQuery native functions to HTMLElements in Javascript在 Javascript 中将 jQuery 原生函数重建为 HTMLElements
【发布时间】:2020-08-06 10:25:21
【问题描述】:

我想重新实现 jQuery 函数。

例如.attr()

我发现了一些线程,例如this

所以我尝试了类似的方法:

HTMLElement.prototype.attr = (pAttributeName, pAttributeValue) => {
  if(pAttributeValue){
    this.setAttribute(pAttributeName, pAttributeValue);
  } else {
      return this.getAttribute(pAttributeName);
  }
};

但它不起作用。我必须先在构造函数中初始化元素吗?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

来自documentation

箭头函数表达式(也称为胖箭头函数)有一个 与函数表达式和词法绑定相比,语法更短 这个值

在您的情况下,this 绑定到 window 对象。

使用常规函数

HTMLElement.prototype.attr = function(pAttributeName, pAttributeValue) {
  if (pAttributeValue) {
    this.setAttribute(pAttributeName, pAttributeValue);
  } else {
    return this.getAttribute(pAttributeName);
  }
};

document.querySelector('h1').attr('id', 'head')
#head {
  color: red;
}
<h1>Heading</h1>

【讨论】:

  • 感谢您非常酷的回答!真的很感激!
猜你喜欢
  • 2020-03-02
  • 2014-02-06
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多