简体   繁体   中英

Extending a DOM element with jQuery

I'd like to extend a DOM element without extending all of them. That is, I'd like a custom class with its own methods and properties, but also be able to treat it as a div. Eg

 MyClass = function(){
    this.foo = "waaa";
 }
 MyClass.prototype.changeText = function(newtext){
    // if this extended $(document.createElement("div")) something
    // like this might be possible
    this.html(newtext);
 }
 MyClass.prototype.alertFoo = function(){
    alert(this.foo);
 }

 var m = new MyClass();
 $("body").append(m);
 m.changetext();

Is this possible?

You can make your class a child class of the jquery generated DIV element:

function MyClass (){
    this.foo = "waaa";
}
MyClass.prototype = $('<div/>');
MyClass.prototype.changeText = function(newtext){
    this.html(newtext);
}
MyClass.prototype.alertFoo = function(){
    alert(this.foo);
}

var m = new MyClass();
$("body").append(m);
m.changeText('appletree');

You could make your own object, like you are doing. Then you can use jQuery's extend method to extend the element.

The problem will come when you want to retrieve the element later. Maybe you can just store the extensions as data of the element like such:

var new_div = $('<div id="new_div" />');
new_div.data('m', new MyClass());

Then to call the functions later, you would do something like:

new_div.data('m').changetext(new_div)

And pass the div as an argument.

You can also do it as a plugin:

jQuery.fn.myKindOfElement = function(msg) {
    var foo = msg; // foo is basically a private member
    this.alertFoo = function() {
        alert(foo);
    };
    this.setFoo = function(msg) {
        foo = msg;
    };
    this.changeText = function(text) {
        // doesn't make sense because html already exists here
        this.html(text);
    };
};

Then for any element:

var myKind = $('<div/>').myKindOfElement('bar');
$('body').append(myKind);
myKind.alertFoo(); // alerts 'bar'
myKind.changeText('blah'); // same as myKind.html('blah')

jQuery won't be able to understand m when you pass it to the append line, because it only accepts strings and elements. Your MyClass will probably have a specific key to hold the element itself (eg this.el = document.createElement("div");), but jQuery won't be able to find that on its own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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