jQuery 文档中写道,选择器上的remove() 会删除与其关联的所有事件。但是在调用删除函数后的以下代码中,与 #this 上的 onclick 关联的警报未删除。我在这里缺少什么?
代码:
<div style="width:100%; min-height:100px; background-color:yellow;" id="add" onclick="remove()">
<ul id="remove" style="width:100%; background-color:purple; padding:4vh;">
<li>
<div id="this" style="width:100%; height:5vh; background-color:red;" onclick=alert("Clicked")>
Abc
</div>
<div style="width:100%; height:5vh; background-color:blue;">
XYZ
</div>
<div style="width:100%; height:5vh; background-color:orange;">
LMN
</div>
</li>
</ul>
</div>
Jquery:
var t = 0;
var sp;
function remove(){
if(t % 2 == 0){
sp = $("#remove").remove();
t++;
}
else{
$("#add").append(sp);
t++;
}
}
最佳答案
.remove()(jquery 文档)
Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.
点击
应避免HTML 属性,因为它会使标记更大且可读性较差。对内容/结构和行为的关注点没有很好地分开,使得错误更难被发现。
你的代码
document.addEventListener("DOMContentLoaded", function() {
var t = 0;
var sp;
function remove(){
if(t % 2 == 0){
sp = $("#remove").remove();
t++;
}
else{
$("#add").append(sp);
t++;
}
}
$('#add').on('click', function(event) {
remove();
});
$('#this').on('click', function(event) {
alert('clicked');
});
});
<html>
<head></head>
<body>
<div style="width:100%; min-height:100px; background-color:yellow;" id="add">
<ul id="remove" style="width:100%; background-color:purple; padding:4vh;">
<li>
<div id="this" style="width:100%; height:5vh; background-color:red;">
Abc
</div>
<div style="width:100%; height:5vh; background-color:blue;">
XYZ
</div>
<div style="width:100%; height:5vh; background-color:orange;">
LMN
</div>
</li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
关于JQuery 分离与删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51812033/