2011-04-11 112 views
0

我是新來的Javascript類,或缺乏對類的真正支持。Javascript類:創建和銷燬元素

在任何情況下,我想創建一個函數,我可以創建和銷燬DOM元素。我可以創建元素但銷燬它們有點棘手。

如何在不提供ID的情況下致電銷燬?

function WorkZone() { 
    this.create = function(id) { 
     $('<div>', { 
      id: id, 
      class: 'work-zone' 
     }).appendTo('body'); 
    } 

    this.destroy = function(id) { 
     $(id).remove(); 
    } 
} 

$(function() { 
    var zone = new WorkZone(); 
    zone.create(); 
    zone.destroy(); 
}); 
+0

比你在沒有一個id破壞會? ? – Neal 2011-04-11 22:22:32

+0

這也應該標記jQuery?有一些'$(...)'... – 2011-04-11 22:23:49

+0

你在這裏或其他框架使用jQuery嗎?你應該添加一個標籤或明確指出哪一個。 – intuited 2011-04-11 22:24:02

回答

0

使用jQuery做的,而不是創建自定義代碼如下:

http://api.jquery.com/category/manipulation/

你會摹等全面的瀏覽器支持和最佳代碼,並能夠使用許多不同種類的選擇器來完成這些類型的DOM操作。

+0

看起來像jQuery已被使用 – Neal 2011-04-11 22:26:25

0

試試這個:

var WorkZone = { 
    wz: null, 
    create: function(id) { 
     this.wz = $('<div>', { 
      id: id, 
      class: 'work-zone' 
     }).appendTo('body'); 
    }, 

    destroy: function() { 
     this.wz.remove(); 
    } 
} 

$(function() { 
    var zone = WorkZone; 
    zone.create('new_id'); 
    zone.destroy(); 
}); 
+0

我認爲OP想創建WorkZone的多個實例。 – RobG 2011-04-11 23:02:48

+0

@RobG OP仍然可以 – Neal 2011-04-11 23:07:13

0

像這樣:

function WorkZone() { 
    this.create = function(id) { 
     this.div = $('<div>', { 
      id: id, 
      class: 'work-zone' 
     }); 
     this.div.appendTo('body'); 
    } 

    this.destroy = function(id) { 
     this.div.remove(); 
    } 
} 
0
function WorkZone(id) { 
    this.create = function() { 
     $('<div>', { 
      id: id, 
      class: 'work-zone' 
     }).appendTo('body'); 
    } 

    this.destroy = function() { 
     $('#'+id).remove(); 
    } 
} 

$(function() { 
    var zone = new WorkZone("ohyeababy"); 
    zone.create(); 
    zone.destroy(); 
}); 

這不是實現自己的最終目標的最佳方式,但它在你的代碼複製立即修復。 :)

2

你只需要保持對元素的引用作爲對象的屬性。然後destroy方法直接引用元素,你甚至不需要一個id。

function WorkZone() { 

    this.create = function(id) { 

     // Remember the element 
     this.element = $('<div>', { 
         id: id, 
         class: 'work-zone' 
         }); 
     // This could be chained to the above, 
     // but it's a lot easier to read if it isn't 
     this.element.appendTo('body'); 
    } 

    this.destroy = function() { 
     // Use element reference 
     this.element.remove(); 
    } 
} 

$(function() { 
    var zone = new WorkZone(); 
    zone.create(); 
    zone.destroy(); 
}); 

但你要好得多穿上WorkZone.prototype的方法,使他們共享,而不是自己的副本每個實例:

function WorkZone() { 
    this.element; 
} 

WorkZone.prototype = { 
    create: function(id) { 
    this.element = $(..)...// create element, add to document 
    }, 
    destroy: function() { 
    this.element.remove(); 
    } 
} 

var zone = new WorkZone(); 
zone.create(id); 
zone.destroy();