点击按钮做某事,然后点击相同的按钮撤消它

click button does something, then click same button undo it

本文关键字:按钮 撤消 然后      更新时间:2023-09-26

我试图让一个按钮通过列表创建一条线,但如果您再次单击它,它将撤销该行。我已经尝试过.toggle(),但它不起作用:

原始代码:

$("div").on("click", ".doneButt", function(e) {
    e.preventDefault();
    $(this).parents("li").css("text-decoration", "line-through");   
});

。切换尝试:

$(".doneButt").toggle(function() {
    $(this).parents("li").css("text-decoration", "line-through");
}, function() {
    $(this).parents("li").css("text-decoration", "none");
});

$(".doneButt").click(function() {
  $(this).parents("li").toggleClass('withline');
});
.withline {
  text-decoration: line-through
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>asdasdasda
    <input type='button' class='doneButt' value='Click' />
  </li>
</ul>

  1. 使用.toggleClass()
$( ".doneButt" ).on("click",function() {
        var style = $(this).attr("style")+"";
        if(style=="undefined")
            $(this).parents("li").css("text-decoration", "line-through");
        else
            $(this).parents("li").removeAttr("style");
        });