我正在尝试制作一个按钮来创建小窗口,您可以在按 X 后关闭该窗口。 我遇到的问题是我只能关闭最后创建的窗口。
function openNote() {
var base = document.createElement('div');
base.id = 'note';
var in_ = document.createElement('div');
in_.id = 'note_in';
var in_2 = document.createElement('div');
in_2.id = 'note_in2';
var ex = document.createElement('div');
ex.id = 'ex';
var ext = document.createTextNode("X");
base.appendChild(in_);
in_.appendChild(in_2);
in_2.appendChild(ex);
ex.appendChild(ext);
document.body.appendChild(base);
document.getElementById('ex').onclick = function(){
var r = document.getElementById('note');
r.parentNode.removeChild(r);
}
}
#note{
background:#819C9A;
height : 200px;
width : 150px;
border: 2px solid;
border-radius: 25px;
border-color:#49706E;
margin:10px;
}
#note_in{
float:left;
height : 35px;
width : 150px;
background:rgba(255,255,255,0.2);
}
#note_in2
{
float:right;
height : 25px;
width : 25px;
margin:5px;
background:#9DCCCA;
border-radius: 15px;
text-align: center;
cursor:pointer;
}
#ex{
margin-top: 4px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="script.js"></script>
</head>
<body>
<button onClick="openNote();">Press me!</button>
</body>
</html>
我对 JavaScript 还很陌生,希望得到任何帮助或建议。
最佳答案
您面临的问题是您创建了多个具有相同 id 的 dom 元素,每页 id 是唯一的。
现在发生的事情是每次您点击“按我!”时发生的情况创建了新的 dom 元素,但 document.getElementById('ex') 只获取树中的第一个元素,因此无论稍后添加多少个元素,您始终将事件绑定(bind)到第一个元素。
修复选项很少:
- 使用类并绑定(bind)到类。
- 检查笔记是否已打开,如果是,请勿打开另一个笔记,或销毁前一个笔记
- 第三个选项使用已创建的 ex 和 base 变量(示例如下)
function openNote() {
var base = document.createElement('div');
base.id = 'note';
var in_ = document.createElement('div');
in_.id = 'note_in';
var in_2 = document.createElement('div');
in_2.id = 'note_in2';
var ex = document.createElement('div');
ex.id = 'ex';
var ext = document.createTextNode("X");
base.appendChild(in_);
in_.appendChild(in_2);
in_2.appendChild(ex);
ex.appendChild(ext);
document.body.appendChild(base);
ex.onclick = function(){
base.parentNode.removeChild(base);
}
}
#note{
background:#819C9A;
height : 200px;
width : 150px;
border: 2px solid;
border-radius: 25px;
border-color:#49706E;
margin:10px;
}
#note_in{
float:left;
height : 35px;
width : 150px;
background:rgba(255,255,255,0.2);
}
#note_in2
{
float:right;
height : 25px;
width : 25px;
margin:5px;
background:#9DCCCA;
border-radius: 15px;
text-align: center;
cursor:pointer;
}
#ex{
margin-top: 4px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="script.js"></script>
</head>
<body>
<button onClick="openNote();">Press me!</button>
</body>
</html>
使用第三个选项,你实际上可以跳过所有 id
关于javascript - 使用纯js创建可关闭的div元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27039177/