选中复选框的触发器功能,不使用.change()

时间:2013-09-21 15:04:08

标签: javascript jquery html checkbox

我有一个动态加载的表,其中每一行都有一个复选框选项,指定的#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>

谢谢, 标记

3 个答案:

答案 0 :(得分:4)

仅在选中复选框时执行操作

$(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

答案 1 :(得分:1)

您需要在函数:checked

中使用is()选择器
<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/

答案 2 :(得分:0)

在html标记中缺少结尾引用(在样式属性之后)

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