【问题标题】:Trigger function from checkbox checked, without using .change()选中复选框的触发功能,不使用 .change()
【发布时间】:2013-09-21 23:09:05
【问题描述】:

我有一个动态加载的表格,其中每一行都有一个复选框选项,分配的#id 为 1,2 或 3。我需要创建一个函数来显示对应于复选框 #id 的隐藏 div检查。我目前正在使用 .change() 来触发该功能,但这最终会在取消选中一个框时显示隐藏的 div,这是我不希望发生的。是否有另一种方法可以仅在“选中”而不是“未选中”时触发此功能。见以下代码:

<tr>
   <td >
      <input id="1" class="link_contact" type="checkbox"/>
   </td>
</tr>
<tr>
   <td >
      <input id="2" class="link_contact" type="checkbox"/>
   </td>
</tr>
<tr>
   <td >
      <input id="3" class="link_contact" type="checkbox"/>
   </td>
</tr>

<div class="1" style="display:none;"> Some Hidden Text</div>
<div class="2" style="display:none;"> Some Hidden Text</div>
<div class="3" style="display:none;"> Some Hidden Text</div>

<script>
$(document).ready(function () {
    $(".link_contact").change(function () {
        $("." + $(this).attr('id')).fadeIn(800);
        $("." + $(this).attr('id')).delay(7000).fadeOut(800);
    });
});
</script>

谢谢, 标记

【问题讨论】:

    标签: javascript jquery html checkbox


    【解决方案1】:

    仅当复选框被选中时才执行操作

    $(document).ready(function () {
        $(".link_contact").change(function () {
            if (this.checked) {
                $("." + this.id).stop(true, true).fadeIn(800).delay(7000).fadeOut(800);
                $('.dialog_warning').fadeOut(800);
            }
        });
    });
    

    演示:Fiddle

    【讨论】:

      【解决方案2】:

      你需要在函数is()中使用:checked选择器

      <script>
      $(document).ready(function () {
          $(".link_contact").change(function () {
              if($(this).is(":checked")) {
                   $("." + $(this).attr('id')).fadeIn(800);
                   $("." + $(this).attr('id')).delay(7000).fadeOut(800);
                   $('.dialog_warning').fadeOut(800);
              }
          });
      });
      </script>
      

      检查这个http://api.jquery.com/checked-selector/

      【讨论】:

      • 谢谢!都尽快给你答案!
      【解决方案3】:

      在您的 html 标记中缺少结束引号(样式属性之后)

      <div class="3" style="display:none;> Some Hidden Text</div>
      

      【讨论】:

      • 谢谢,但这只是一个错字。不是我想要的。
      • 这个缺少的报价导致了这个错误;)
      猜你喜欢
      • 2010-10-17
      • 1970-01-01
      • 2015-01-15
      • 2017-02-14
      • 1970-01-01
      • 2015-12-16
      • 2016-09-07
      • 1970-01-01
      • 2018-06-05
      相关资源
      最近更新 更多