创建和删除JavaScript 中的元素
function labelOnClick () {
function makeDivId(id) {
return id + "_div";
};
var div = this.getElementById(makeDivId(this.id));
if (div) {
div.parentNode.removeChild(div);
} else {
div = document.createElement("div");
div.innerHTML = "welcome";
div.id = makeDivId(this.id);
this.appendChild(div);
}
}
<label id="1" onclick="labelOnClick()" > BROWSER </label>
<label id="2" onclick="labelOnClick()"> GAMING CONSOLE </label>
在上面的示例中,我尝试在单击标签时创建一个 div
元素,并在再次单击标签时删除创建的 div
元素,但它不起作用。
function labelOnClick () {
function makeDivId(id) {
return id + "_div";
};
var div = this.getElementById(makeDivId(this.id));
if (div) {
div.parentNode.removeChild(div);
} else {
div = document.createElement("div");
div.innerHTML = "welcome";
div.id = makeDivId(this.id);
this.appendChild(div);
}
}
<label id="1" onclick="labelOnClick()" > BROWSER </label>
<label id="2" onclick="labelOnClick()"> GAMING CONSOLE </label>
In the above example, I'm trying to create a div
element when a label is clicked and remove the created div
element when the label is clicked again, but it's not working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码中存在几个问题:
当在事件处理函数内内联分配事件处理程序时 (
label onclick="..."
)this
将指向全局对象(窗口
)。您可以将this
作为参数传递给函数。getElementById()
的结果分配给变量时会失败(如果我错了,请有人纠正我)。像这样的东西会起作用:
jsFiddle 演示
You have several problems in your code:
When assigning event handlers inline (
label onclick="..."
) inside the event handler functionthis
will point to the global object (window
). You can passthis
as an argument to the function.Certain browsers will fail when assigning the result of
getElementById()
to a variable if no element is found (someone correct me if I'm wrong).Something like this would work:
jsFiddle Demo
我的建议是不要使用 javascript 添加 div,而是在单击时更改 div 标签的可见性样式属性。
My suggestion would be to not add the div using the javascript, but to change the div tag's visibility style property on click..
您尝试使用“this”关键字代替“document”,但该关键字不起作用,因为“this”指向 labelOnClick 函数。
我写这篇文章假设您正在使用支持事件对象的“目标”属性的东西(例如不是 Internet Explorer)。如果您需要跨浏览器支持,您可以手动完成或使用 jQuery 或 Prototype 等框架。
按照原始代码的编写方式,我假设您想要每个标签一个 div,并且我猜测了位置(紧随标签之后)。
You are trying to use the "this" keyword in place of "document", which does not work since "this" is pointing to the labelOnClick function.
I wrote this assuming you are using something that supports the "target" property of the event object (e.g. not internet explorer). If you need cross browser support, you can do it manually or use a framework like jQuery or Prototype.
The way the original code was written, I assumed that you wanted a div per label and I guessed at the positioning (immediately following the label).