【问题标题】:Jquery checkbox checked and unchecked eventsJquery 复选框选中和未选中事件
【发布时间】:2018-12-28 15:46:33
【问题描述】:

我在 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”应转换为 Task(使用 del 或罢工标签后输出),如果未选中复选框,则应再次将其转换为上一个类似于“任务 2”的​​形式。

【问题讨论】:

  • 我发布了一个不同的解决方案,只有css

标签: javascript jquery html css jquery-plugins


【解决方案1】:

当复选框被选中和取消选中时,您可以使用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>

【讨论】:

  • 谢谢。有效。但它只对一个复选框起作用,如果我想在 html 代码中调用这个函数 5 到 6 次,那我该怎么办?
  • @Deepak 你需要为此分享你的 HTML。可能为此创建一个新问题
【解决方案2】:

您只需使用CSS 即可达到此目的,使用选择器更改下一个label 的:selected checkbox 的样式:

input[type='checkbox']:checked + label {
  text-decoration: line-through;
}
<div class="checkbox">
   <input type="checkbox" id="checkbox1" /><label>Task 1</label>
</div>
<div class="checkbox">
   <input type="checkbox" id="checkbox2" /><label>Task 2</label>
</div>

【讨论】:

  • 是的,我可以这样做,但我想通过 jquery 做到这一点,那怎么可能?
  • 很简单,就像@Ankit的思路一样,切换类是这样的:jsfiddle.net/xpvt214o/454334看看找什么
猜你喜欢
  • 2015-01-31
  • 2017-04-21
  • 1970-01-01
  • 2013-08-04
  • 2013-01-23
  • 2020-04-08
  • 1970-01-01
  • 2012-06-29
  • 2014-04-28
相关资源
最近更新 更多