如何删除具有相同 class 的所有元素
How to remove all elements with the same class
所以我有一个系统,网站的用户可以创建 div,所有这些 div 都有不同的 class 名称,所有这些 div's 也将创建一个具有相同 class 的删除按钮。如何在单击按钮时删除按钮和具有相同 class 的 div。
我想应该是这样的:
$("div.Test").remove();
仅比带有 this 标签。
$("button").click(function(){
$("div."+$(this).attr('class')).remove();
// $("."+$(this).attr('class')).remove(); to remove both button and div
});
假设 button
只有一个 class 名称与 div 的 class 名称相匹配。
您需要一种选择所有按钮的方法。我将创建带有可用于访问的 class 的按钮,并使用数据属性来保存要删除的 div 的 class。像这样:
<button class="remove-btn" data-remove="div-class">Remove</button>
那么你可以这样做:
$(function(){
$('.remove-btn').on("click", (function(){
var remove = $(this).data('remove');
$('.' + remove).remove();
$(this).remove();
});
});
在您的按钮的点击事件中:
var thisClass = $(this).attr("class");
$('div.' + thisClass).remove();
首先你需要得到你点击的按钮的class,然后找到具有相同class的div并移除它。稍后,只需删除您单击的按钮:
$("#your-button-id").click(function() {
var className = $(this).attr('class'); // find the button class
$('div.' + className).remove(); // remove the div with the same class as the button
$(this).remove(); // remove the button
});
所以我有一个系统,网站的用户可以创建 div,所有这些 div 都有不同的 class 名称,所有这些 div's 也将创建一个具有相同 class 的删除按钮。如何在单击按钮时删除按钮和具有相同 class 的 div。
我想应该是这样的:
$("div.Test").remove();
仅比带有 this 标签。
$("button").click(function(){
$("div."+$(this).attr('class')).remove();
// $("."+$(this).attr('class')).remove(); to remove both button and div
});
假设 button
只有一个 class 名称与 div 的 class 名称相匹配。
您需要一种选择所有按钮的方法。我将创建带有可用于访问的 class 的按钮,并使用数据属性来保存要删除的 div 的 class。像这样:
<button class="remove-btn" data-remove="div-class">Remove</button>
那么你可以这样做:
$(function(){
$('.remove-btn').on("click", (function(){
var remove = $(this).data('remove');
$('.' + remove).remove();
$(this).remove();
});
});
在您的按钮的点击事件中:
var thisClass = $(this).attr("class");
$('div.' + thisClass).remove();
首先你需要得到你点击的按钮的class,然后找到具有相同class的div并移除它。稍后,只需删除您单击的按钮:
$("#your-button-id").click(function() {
var className = $(this).attr('class'); // find the button class
$('div.' + className).remove(); // remove the div with the same class as the button
$(this).remove(); // remove the button
});