JQuery 分离与删除

标签 jquery

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/

相关文章:

javascript - jQuery 菜单 - 在下拉悬停时保持菜单处于事件状态

javascript - jquery错误$不是函数

jquery - 如何使用 jQuery 进行标签切换

jquery - 将变量插入数据属性,AJAX

javascript - jquery用animate上下滑动不会停止滑动

javascript - Materialise(框架)字符数

jquery - Google Analytics(分析)被阻止在新窗口中打开

javascript - jquery.val() 在页面上有效,在页面外无效?为什么?

javascript - jquery 如果不工作

jquery - 固定表格列宽(使用 colgroup)在 IE 和 Safari 中删除列后不起作用