gpt4 book ai didi

javascript - 如何通过单击元素删除类

转载 作者:行者123 更新时间:2023-12-02 21:22:20 24 4
gpt4 key购买 nike

在我的代码片段中,有 3 个按钮,我想使用 erase 按钮。

单击erase按钮后,我想通过逐一单击每个单元格来Removeclass

有什么方法吗?

谢谢

var $ = jQuery;
var style ='';
let clicked=[];

$('.click_btn').on('click', function(e) {
e.preventDefault();
style = $(this).data().style;
})

$('.click_td').on('click', function(){
$(this).removeClass('style1 style2').addClass(style)
let clickedID=$(this).attr('id');
clicked.push(clickedID);
})
.style1 {
background: rgb(255, 0, 255);
border-radius: 5px;
}

.style2 {
background: rgb(0, 255, 255);
border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="click_td" id=0>color</td>
<td class="click_td" id=1>color 2</td>
<td class="click_td" id=2>color 3</td>
<td class="click_td" id=3>color 4</td>
<td class="click_td" id=4>color 5</td>
</tr>
</table>
<button class="click_btn" data-style="style1">can be erased</button>
<button class="click_btn" data-style="style2">cannot be erased</button>
<button class="erase">erase</button>

最佳答案

您可以尝试添加/删除一个类,您可以根据该类删除样式类:

var $ = jQuery;
var style ='';
//let clicked=[];

$('.click_btn').on('click', function(e) {
e.preventDefault();
style = $(this).data().style;
$('.erase').removeClass('erase-clicked');
})

$('.click_td').on('click', function(){
$(this).addClass(style);
let clickedID=$(this).attr('id');
if($('.erase').hasClass('erase-clicked')){
$(this).removeClass('style1 style2')
}
});

$('.erase').click(function(){
$(this).addClass('erase-clicked');
});
.style1 {
background: rgb(255, 0, 255);
border-radius: 5px;
}

.style2 {
background: rgb(255, 0, 255);
border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="click_td" id=0>color</td>
<td class="click_td" id=1>color 2</td>
<td class="click_td" id=2>color 3</td>
<td class="click_td" id=3>color 4</td>
<td class="click_td" id=4>color 5</td>
</tr>
</table>
<button class="click_btn" data-style="style1">can be erased</button>
<button class="click_btn" data-style="style2">cannot be erased</button>
<button class="erase">erase</button>

关于javascript - 如何通过单击元素删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60814191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com