Reputation: 5299
I would like to undo
only if its class is erasable (can be erased
class style1
)
In my code,I could undo
but I couldn't distinguish them. It seems class
must be stored in some arrays.
If someone has some idea please let me know.
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);
console.log(clicked);
})
$("#undo").on('click',function() {
if(clicked.length) {
let lastClicked = clicked.pop();
$(`td#${lastClicked}`).removeClass();
}
})
.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 id="undo">undo</button>
Upvotes: 0
Views: 78
Reputation: 201
I changed your Undo function a little bit, I am checking if the last clicked element has the Class style1
and if the element got this Class it should be removed.
$("#undo").on('click',function() {
if(clicked.length) {
let lastClicked = clicked.pop();
if ($('#' + lastClicked).hasClass('style1')) {
$('#' + lastClicked).removeClass('style1')
}
}
fiddle here: https://jsfiddle.net/cznfyrsx/1/
hope this could answer your question :)
Upvotes: 1