【发布时间】:2012-07-03 04:42:02
【问题描述】:
我刚刚开始使用 JavaScript 中的 OOP。我想创建一个自定义“面板”。这是我目前所拥有的:
function ShinyPanel(css, attributes)
{
this.container = $(document.createElement("div")).addClass("shinyPanel");
this.titleBar = $(document.createElement("div")).addClass("shinyPanelTitleBar").appendTo(this.container);
this.topShine = $(document.createElement("div")).addClass("shinyPanelTopShine").appendTo(this.container);
this.leftShine = $(document.createElement("div")).addClass("shinyPanelLeftShine").appendTo(this.container);
this.content = $(document.createElement("div")).addClass("shinyPanelContent").appendTo(this.container);
if (!css) css = {};
if (!attributes) attributes = {};
this.css = css;
$(this.container).css(this.css);
this.title = attributes["title"];
$(this.titleBar).html(this.title);
}
现在我可以实例化这个对象并通过以下方式将其附加到正文中:
var panel = new ShinyPanel({position:"absolute", top:"25%", width:"300px", height:"200px"}, {title:"Test"});
$("body").append(panel.container);
我的问题是,有没有办法让对象本身成为一个 div,从而消除对“容器”div 的需要?然后我就可以打电话给$("body").append(panel);。
容器 div 放在那里对我来说并不是什么麻烦,更适合我……想学习正确的做事方式。
我尝试了this = document.createElement("div");,但出现错误:invalid assignment left-hand side。
【问题讨论】:
-
return this.container;不起作用吗? :) -
当时我没有想到这一点,但是在@PaulPhillips 在他的回答中提出建议之后,我正在尝试它,并且由于某种原因,将元素附加到 panel.content 不起作用。不过,我仍然在弄乱它,看看我能不能弄明白。
-
我建议您检查一下 jQuery UI 是如何工作的,因为我认为这大致就是您想要做的。
-
@Jack:我想我会使用 jQuery UI。感谢您的建议。如果您想发布答案,我会接受。
标签: javascript jquery oop custom-component