2009-07-23 9 views
6

DOM 요소를 모두 확장하지 않고 확장하고 싶습니다. 즉, 자체 메서드 및 속성을 가진 사용자 지정 클래스를 원하지만 div로 처리 할 수도 있습니다. 예 :jQuery로 DOM 요소 확장하기

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

이것은 가능합니까?

답변

5

DIV 요소를 생성 :

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'); 
+1

이것은 플러그인을 확장 할 때도 유용합니다. 따라서 this.hide가 실제로 this.fadeOut이되도록 함수를 재정의하십시오. 클래스 내부에서 __proto__를 사용하고 다음과 같이 기본 jquery 객체를 전달합니다. [link] (http://pastebin.com/hFUnqTBQ) – Shanimal

0

jQuery는 문자열과 요소 만 허용하기 때문에 추가 라인에 전달할 때 m을 이해할 수 없습니다. MyClass에는 요소 자체를 보유 할 특정 키가있을 수 있습니다 (예 : this.el = document.createElement ("div");).하지만 jQuery는 자체적으로 해당 키를 찾을 수 없습니다.

+0

위의 내용은 내가 한 일의 예일뿐입니다. 본질적으로 나는 다음과 같은 것을 찾고있다. MyClass : document.createElement ("div") 즉, jquery에게 특정 키를 찾지 말고 jquery가 객체 자체가 요소, 즉 내 객체는 요소를 확장합니다. – pondermatic

1

당신이하는 것처럼 자신 만의 물건을 만들 수 있습니다. 그런 다음 jQuery의 extend method을 사용하여 요소를 확장 할 수 있습니다.

+0

작동하지 않습니다. more() { \t \t \t \t this.myname = "more!" \t \t \t} \t \t \t more.prototype.alert = 함수() { \t \t \t \t 경고 ('경고!') \t \t \t} \t \t \t \t \t \t var에 사업부 = $ (문서 .createElement ("div"))); \t \t \t div.html ("this is s"); \t \t \t \t \t \t $.extend (true, div, more); . \t \t \t \t \t \t $ (문서) .ready (함수() { \t \t \t \t $ ("본체") (DIV) 추가; \t \t \t \t div.alert(); \t \t을 \t \t 경고 (div.myname); \t \t \t}); – pondermatic

+0

맞아요, 당신은 객체가 필요합니다.이 객체가'extend' 메소드로 작동하는 것은 아닙니다. '$ .extend (true, div, new more); – geowa4

1

나중에 요소를 검색 할 때 문제가 발생합니다. 어쩌면 당신은 바로 그러한 같은 요소의 데이터로 확장을 저장할 수 있습니다 :

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

그런 다음 나중에 함수를 호출하기 위해, 당신은 같은 것을 할 것 :

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

을 그리고 인수로 사업부를 전달합니다.

+0

그래, 이런 일이 가능하다는 것을 깨닫는다. 그러나 그것은 확실히 우아하지 않다. 자바 스크립트에 대한 모든 과대 광고가 너무 좋아서, jquery duck과 같은 방식으로 내 맞춤 수업을 진행할 수 없다는 사실이 끔찍합니다. – pondermatic

1
또한 플러그인으로 그것을 할 수

: 모든 요소에 대한 다음

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

: 당신은 당신의 클래스 JQuery와의 하위 클래스를 만들 수 있습니다

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