【问题标题】:detecting if a checkbox is ticked inside a target div with jQuery使用 jQuery 检测是否在目标 div 内勾选了复选框
【发布时间】:2013-01-15 16:12:22
【问题描述】:

我有以下标记,结束跨度标记下方是一个数字列表项。

<div class="header_block">
   <span class="background_flag_container">
      <input id="block_background" type="checkbox" name="block_background">
      <span class="background_flag_text">Has Banner Background</span>
   </span>
   ...
</div>

这是我的 jQuery。我要做的是检查是否选中了唯一一个名为“block_background”的复选框。页面上有许多 'block_background' 复选框,但在 $(this) 中只有 一个,即 .header_block div。

$(this).find(".background_flag_container input:checkbox[name='block_background']").each(function(){
   if ($(this).checked) {
      console.log('is checked');
   }
});

如何检查是否已检查?

【问题讨论】:

  • jQuery 很棒,但你做错了。正如@wirey 解释的那样,使用this.checked 也是你的选择器是错误的,如果那确实是你的html,你可以使用$(this).find('input'),我不确定this 在你的代码中是什么,可能可以进行更多优化。
  • @Khez 没问题,当有人指出我做错了什么时(以你所做的方式),我没有问题。
  • @crmpicco 不知何故,我觉得你认为这是一种侮辱,并不是那个意思。只是想澄清一下...
  • @Khez 不,相反。我回答说你没有只是带着讽刺的评论飞到那里......我赞成你的评论。感谢您的帮助。

标签: javascript jquery html forms checkbox


【解决方案1】:

您可以使用is(':checked') 来检查是否选择了某些内容

   $(this).find(".background_flag_container input:checkbox[name='block_background']").each(function(){
       if ($(this).is(':checked')) {
          console.log('is checked');
       }
    });

虽然看到复选框的 ID block_background 应该是唯一的。你可以这样做:

if ($('#block_background').is(':checked')) {
    console.log('is checked');
}

【讨论】:

    【解决方案2】:
    $("input#block_background]").is(':checked')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 2016-08-20
      • 2020-11-04
      • 2013-02-21
      • 2011-01-13
      • 1970-01-01
      • 2015-08-13
      相关资源
      最近更新 更多