javascript - 为所有对象创建一个方法,js vanilla?
问题描述
我想创建一个可以从任何对象调用的方法。
例如,我可以创建以下方法:
document.el=function(e){return this.getElementById(e);}
现在我可以打电话了:
document.el("myDiv") //returns <div id="myDiv"></div>
但我想让所有对象都可以使用该方法,所以我可以调用:
document.body.el("myDiv") //returns document.body.el is not a function
我可以从文档的所有子元素中使用它吗?也许通过递归循环?基本上我正在寻找的是类似的东西:
*.el=function(e)...
解决方案
尽管您可能不应该扩展 DOM,但您可以通过向 的原型添加方法来实现HTMLElement
,例如:
HTMLElement.prototype.el = function (id) {
return this.getElementById(id);
};
<div id='div-id'><p id='p-id'>Hello</p></div>
document.getElementById('div-id').el('p-id').innerText; // `Hello`
推荐阅读
- reactjs - 为什么 useEffect 外部的函数会被调用,而 useEffect 内部没有依赖数组的函数却不会?
- c# - C# Linq 如何通过流读取 xml 并过滤特定元素
- architecture - DDD:直接聚合处理域事件?
- python-3.x - Discord.py modmail系统
- php - 如何从时间戳中仅提取 php laravel 查询中的日期?
- sql - Salesforce SQL 查询活动设置错误
- javascript - 在循环后尝试使用用户在 JOptionPane 中输入的数据
- hugo - Hugo-ish 引用静态文件(资源)的方式_indirectly_所以文件名可以在一个地方更改并且所有内容链接都会更改
- javascript - Javascript 问题:常量未运行。不断发送电子邮件
- python - 找到矩阵中的最小列数,以确保所有行都是唯一的