简体   繁体   English

扩展DOM元素

[英]Extending DOM elements

Im working on a jQuery/Zepto slider plugin and wanted ask you about extending dom elements. 我正在开发jQuery / Zepto滑块插件,想询问您有关扩展dom元素的问题。 I know that this method is not very elegant for different browsers environment but its make life so much easier. 我知道这种方法对于不同的浏览器环境不是很好,但是它使生活变得更加轻松。

Also to make names unique ive added all methods into one object 'pluginName' 为了使名称唯一,我将所有方法都添加到一个对象“ pluginName”中

So each slider item will get a set of custom methods: 因此,每个滑块项将获得一组自定义方法:

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(){};
}

Is this method worth a try? 这种方法值得一试吗? Are there any huge issues with custom element methods? 自定义元素方法有什么大问题吗? Im not sure am i going to right direction. 我不确定我会朝正确的方向前进。 Thanks 谢谢

Notice that document.createElement('div'); 注意document.createElement('div'); returns an instance of HTMLDivElement : 返回HTMLDivElement的实例:

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

Therefore, you can extend the HTMLDivElement class by simply adding properties to its .prototype object: 因此,您可以通过简单地将属性添加到其.prototype对象来扩展HTMLDivElement类:

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

Or even shorter: 甚至更短:

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

EDIT If you just want to add new methods to a single div, try the following: 编辑如果只想向一个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

Since you mentioned jQuery, how about something like this: 既然您提到了jQuery,那么这样的事情怎么样:

var $div = $('<div/>').data({ 
    pluginName: { 
        doStuff: function(s){ console.log('hello ' + s); } 
    } 
});

$div.data('pluginName').doStuff('world');

http://jsfiddle.net/LHk8j/ http://jsfiddle.net/LHk8j/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM