单击按钮执行某些操作,然后单击相同按钮撤消它

时间:2016-10-25 06:19:34

标签: javascript jquery

我正在尝试按一个按钮在列表中创建一条线,但如果再次单击它,它将撤消直通线。我试过.toggle(),但它不起作用:

原始代码:

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

.toggle attempt:

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

2 个答案:

答案 0 :(得分:5)



$(".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>
&#13;
&#13;
&#13;

  1. 使用.toggleClass()

答案 1 :(得分:0)

$( ".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");
        });