test
= custom js code
add Event Listeners to #c1 Elements
<script #js>
</script>
test
附加到#js
<script #js>
</script>
(((这是一个问题)))) Add Event Listeners to #c2 Elements
.box6
(((这是一个问题))))
问题4
即使我删除了<script #js>
Custom Code Appened for #c1 Elements
</script>
,
#c1 Elements
仍然可以点击...他们表现得好像<script #js>
仍在那里
问题6
这是真的从记忆中删除了......还是类似于问题4 ...意思是它在那里......只是看不到。如果它还在内存中...如何删除它?
抬头
这是一个普遍的问题......不只是Event Listeners
,而是console.log
,alerts
,......删除<script #js>
后......与<script #js>
相关的任何内容都不会发生这应该是从记忆中消失的。
let test = `
let container = document.getElementById("c1")
let clicked = container.getElementsByClassName("boxes");
for (let i = 0; i < clicked.length; i++) {
clicked[i].addEventListener('click', b);
}
function b() {
if(this.classList.contains("clicked")) {
this.classList.remove("clicked");
}
else {this.classList.add("clicked");}
}
`;
// Creating Script Tag with #js
// And appending -test- var to it
let script = document.createElement('script');
script.type = 'text/javascript';
script.id = 'js';
script.text = test;
document.body.appendChild(script);
// I deleted #js
// Yet #c1 .boxes event listeners are still attached to divs?
// They are not suppose to be clickable if I deleted #js
// What's going on
let deleteScript = document.getElementById('js');
deleteScript.parentNode.removeChild( deleteScript );
// This code will stay here
let container2 = document.getElementById("c2")
let clicked2 = container2.getElementsByClassName("boxes");
for (let i = 0; i < clicked2.length; i++) {
clicked2[i].addEventListener('click', b2);
}
function b2() {
if(this.classList.contains("clicked2")) {
this.classList.remove("clicked2");
}
else {this.classList.add("clicked2");}
}
// I deleted .box6
// How to remove it properly from DOM… Out of memory
let deleteDiv = document.getElementById('here');
deleteDiv.parentNode.removeChild( deleteDiv );
body {
background: #E7F0F6;
}
.container {
width: calc(100%-20px);
height: 100%;
display: flex;
}
.boxes {
width: 25%;
height: 80px;
background: white;
margin: 10px;
box-shadow: 0px 0px 0px 1px #36BCFF;
border-radius: 15px;
transition: .3s;
text-align: center;
font-size: 60px;
color: #E7F0F6;
line-height: 80px;
}
.boxes:hover {
box-shadow: 0px 0px 0px 1px #36BCFF, 0px 0px 15px rgba(0, 0, 0, 0.25);
}
.clicked {
background: #36BCFF;
color: white;
}
.clicked2 {
background: #637182;
color: white;
}
<div id="c1" class="container">
<div class="boxes box1">1</div>
<div class="boxes box2">2</div>
<div class="boxes box3">3</div>
<div class="boxes box4">4</div>
</div>
<div id="c2" class="container">
<div class="boxes box5">5</div>
<div id="here" class="boxes box6">6</div>
<div class="boxes box7">7</div>
<div class="boxes box8">8</div>
</div>
答案 0 :(得分:1)
您无法删除导致浏览器评估某些代码并期望它消失的脚本标记
但是您可以使用removeEventListener来取消注册事件侦听器,
您可以操作使用脚本标记声明的变量函数。
答案 1 :(得分:0)
无法完成...脚本标记在呈现脚本标记后立即进行评估。并且无法撤消或禁用。您需要重新创建元素或删除附加到DOM元素的事件侦听器。
垃圾收集器从内存中删除不再可以从某个地方引用