Javascript 类:创建和销毁元素
我是 Javascript 类的新手,或者缺乏对类的真正支持。
无论如何,我想创建一个可以创建和销毁 DOM 元素的函数。我可以创建元素,但销毁它们有点棘手。
如何在不提供 ID 的情况下调用 destroy ?
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();
});
I'm new to Javascript Classes, or lack of real support for classes.
In any case, I'd like to create a function with which I can create and destroy DOM elements. I'm ok with creating the elements but destroying them is a bit trickier.
How can I call destroy without having to provide the 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();
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只需将对元素的引用保留为对象的属性即可。 destroy 方法直接引用该元素,甚至不需要 id。
但最好将方法放在 WorkZone.prototype 上,以便共享它们,而不是每个实例都有自己的副本:
You just need to keep a reference to the element as a property of the object. The destroy method then has a reference directly to the element, you don't even need an id.
But you are much better to put the methods on WorkZone.prototype so they are shared, rather than each instance having its own copy:
使用 jQuery 来执行此操作,而不是创建自定义代码:
http://api.jquery.com/category/manipulation /
您将获得完整的浏览器支持和最佳代码,以及使用许多不同类型的选择器进行此类 DOM 操作的能力。
Use jQuery to do this instead of creating custom code:
http://api.jquery.com/category/manipulation/
You will get full browser support and optimal code and the ability to do these sorts of DOM manipulations with lots of different kinds of selectors.
试试这个:
try this:
就像这样:
Like so:
这不是实现最终目标的最佳方法,但它可以立即修复代码中的重复问题。 :)
This is not the optimal way to achieve your end goal, but it is the immediate fix for the duplication in your code. :)