首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Javascript中将jQuery本机函数重构为HTMLElements

在Javascript中将jQuery本机函数重构为HTMLElements
EN

Stack Overflow用户
提问于 2020-08-06 10:25:21
回答 1查看 42关注 0票数 0

我想重新实现jQuery函数。

例如,.attr()

我找到了一些像这样的线程。

所以我尝试了这样的方法:

代码语言:javascript
复制
HTMLElement.prototype.attr = (pAttributeName, pAttributeValue) => {
  if(pAttributeValue){
    this.setAttribute(pAttributeName, pAttributeValue);
  } else {
      return this.getAttribute(pAttributeName);
  }
};

,但它不起作用。我必须先在构造函数中插入元素吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-06 10:37:06

来自文档

与函数表达式相比,箭头函数表达式(也称为fat箭头函数)的语法更短,并在词汇上绑定此值。

在您的示例中,this被绑定到window对象。

使用正则函数的

代码语言:javascript
复制
HTMLElement.prototype.attr = function(pAttributeName, pAttributeValue) {
  if (pAttributeValue) {
    this.setAttribute(pAttributeName, pAttributeValue);
  } else {
    return this.getAttribute(pAttributeName);
  }
};

document.querySelector('h1').attr('id', 'head')
代码语言:javascript
复制
#head {
  color: red;
}
代码语言:javascript
复制
<h1>Heading</h1>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63281588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档