[英]jquery click append and remove append second click
I am trying to make a append menu on click div. 我试图在单击div上添加一个追加菜单。 But i have one question here. 但是我在这里有一个问题。 How can i remove appended elements after second click. 第二次单击后如何删除附加的元素。 Anyone can help me in this regard ? 在这方面有人可以帮助我吗?
This is the DEMO page from codepen.io 这是来自codepen.io的DEMO页面
Js JS
$(document).ready(function(){
$("body").on("click", ".menu-button", function(event){
event.preventDefault();
$(".menu-container").append('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading… </span></div></div>');
});
});
Seems like toggling the element instead of adding it would be better, but you could just put a check 好像切换元素而不是添加元素会更好,但是您可以检查一下
var childNodes = $(".menu-container").children();
if (childNodes.length) {
childNodes.remove();
} else {
$(".menu-container").append("...");
}
Append the content only if the content not exist. 仅当内容不存在时才附加内容。
$(document).ready(function() {
$("body").on("click", ".menu-button", function(event) {
event.preventDefault();
if (!$('.button').length) {
$(".menu-container").append('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading… </span></div></div>');
} else {
$(".menu-container").html(''); // Empty after
}
});
});
Here's another solution I've called the dblclick
event to empty the contents of the menu-container
.This empties the entire div.Incase you want to remove the last child, you can find the length and remove the last one that way. 这是另一个我称为dblclick
事件的解决方案,用于清空menu-container
的内容,这将清空整个div。如果要删除最后一个孩子,则可以找到长度并以这种方式删除最后一个孩子。
$("body").on("dblclick", ".menu-button", function(event){
$(".menu-container").empty();
});
By no means the most elegant solution but probably the easiest: 绝不是最优雅的解决方案,但可能是最简单的解决方案:
$(document).ready(function(){
$("body").on("click", ".menu-button", function(event){
event.preventDefault();
if($('.menu-container').html().length > 0) {
$(".menu-container").html(null)
}
else {
$(".menu-container").html('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading… </span></div></div>');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.