2011-04-11 111 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();