如何撤消类更改并将类数据存储在 html 表中

我undo只想在它的类是可擦除的(can be erased类style1)的情况下


在我的代码中,我可以undo但我无法区分它们。它似乎class必须存储在某些数组中。


如果有人有什么想法,请告诉我。


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>


江户川乱折腾
浏览 100回答 1
1回答

呼如林

我稍微更改了您的撤消功能,我正在检查最后一次单击的元素是否具有类style1,如果元素具有该类,则应将其删除。&nbsp; $("#undo").on('click',function() {&nbsp; &nbsp; if(clicked.length) {&nbsp; &nbsp; &nbsp; let lastClicked = clicked.pop();&nbsp; &nbsp; &nbsp; if ($('#' + lastClicked).hasClass('style1')) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$('#' + lastClicked).removeClass('style1')&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }在这里摆弄:https ://jsfiddle.net/cznfyrsx/1/
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript