首页 > 解决方案 > Jquery 复选框选中和未选中事件

问题描述

我在 html 中开发了一个代码,其中复选框由 jquery 管理。

<tr>
    <td>
      <div class="checkbox">
        <label><input type="checkbox" id="checkbox2"></label>
      </div>
    </td>

    <td><p id="taks2">Task 2</p></td>

    <td><span class="glyphicon glyphicon-trash"></span></td>        
  </tr>

jquery 脚本是这样的:

<script>
    $(document).ready(function(){
        $('#checkbox2').click(function(){
            if($(this).is(":checked")){

                $('#taks2').replaceWith('<s>' + $('#task2').text() + '</s>');


            }
            else if($(this).is(":not(:checked)")){

            }
        });
    });
</script>

如果用户选中了复选框,则“任务 2”应转换为任务(使用 del 或罢工标签后输出),如果未选中该复选框,则应再次将其转换为以前的形式,如“任务 2”。

标签: javascriptjqueryhtmlcssjquery-plugins

解决方案


您可以使用CSS类添加和删除复选框时添加和删除:

$(document).ready(function(){
  $('#checkbox2').click(function(){
      if($(this).is(":checked")){
        $('#taks2').addClass('strike');
      } else {
        $('#taks2').removeClass('strike');
      }
  });
});
.strike{
  text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <div class="checkbox">
      <label><input type="checkbox" id="checkbox2"></label>
    </div>
  </td>

  <td><p id="taks2">Task 2</p></td>

  <td><span class="glyphicon glyphicon-trash"></span></td>        
</tr>

您还可以使用以下方式缩短代码toggleClass()

$(document).ready(function(){
  $('#checkbox2').click(function(){
      var isChecked = $(this).is(":checked");
      $('#taks2').toggleClass('strike', isChecked);
  });
});
.strike{
  text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <div class="checkbox">
      <label><input type="checkbox" id="checkbox2"></label>
    </div>
  </td>

  <td><p id="taks2">Task 2</p></td>

  <td><span class="glyphicon glyphicon-trash"></span></td>        
</tr>


推荐阅读