gpt4 book ai didi

javascript - 扩展 DOM 元素

转载 作者:行者123 更新时间:2023-11-30 05:38:59 26 4
gpt4 key购买 nike

我正在开发一个 jQuery/Zepto slider 插件,想问问你关于扩展 dom 元素的问题。我知道这种方法对于不同的浏览器环境来说不是很优雅,但它让生活变得更加轻松。

为了使名称唯一,我将所有方法添加到一个对象“pluginName”中

所以每个 slider 项都会得到一组自定义方法:

item = document.createElement('div');
itemMethods(item); // add methods to item element

itemMethods = function(el){
el.pluginName= {};
el.pluginName.getIndex = function(){};
el.pluginName.setLocalData = function(){};
el.pluginName.getLoaclData = function(){};
}

这个方法值得一试吗?自定义元素方法有什么大问题吗?我不确定我是否会朝着正确的方向前进。谢谢

最佳答案

请注意 document.createElement('div'); 返回 HTMLDivElement 的实例:

var div = document.createElement('div');
console.log(div, div.constructor === HTMLDivElement); // HTMLDivElement, true

因此,您可以通过简单地向其 .prototype 对象添加属性来扩展 HTMLDivElement 类:

HTMLDivElement.prototype.pluginName = {};
HTMLDivElement.prototype.pluginName.getIndex = function () {};
HTMLDivElement.prototype.pluginName.getLocalData = function () {};
HTMLDivElement.prototype.pluginName.setLocalData = function () {};

或者更短:

HTMLDivElement.prototype.pluginName = {
getIndex: function () {},
getLocalData: function () {},
setLocalData: function () {}
};

编辑如果您只想向单个 div 添加新方法,请尝试以下操作:

var itemMethods = function (el) {
var index = 0;
var data = {};
el.pluginName = {
getIndex: function () {
// access the element by el
},
getLocalData: function () {
// access the element by el
},
setLocalData: function () {
// access the element by el
}
};
};

item = document.createElement('div');
itemMethods(item); // add methods to item element

关于javascript - 扩展 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21883818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com