【问题标题】:Click on the checkbox inside div which changes the state of the checkbox. jQuery单击 div 内的复选框,它会更改复选框的状态。 jQuery
【发布时间】:2016-08-31 00:46:23
【问题描述】:

有人可以帮我解决这个问题吗?

$('.check_group').click(function () {
    var check = $(this).children('input')[0];
    check.checked = !check.checked;
    alert(check.checked);
    //run something else
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="check_group" style="background-color: rgb(200, 138, 59);">
  <input type="checkbox" />
</div>

所以,当我点击复选框时 - 更改复选框的状态,然后触发 jQuery 和状态更改回来。

如何使当你点击 div / Checkbox - 复选框发生变化并且有警报?

【问题讨论】:

  • 不错的挑战!!!注意到在 Firefox 中(在 47 上选中)它可以按预期工作,但在 Google chrome 上却没有,而且我没有勇气在 IE 上进行检查......哈哈
  • 究竟是什么不起作用?在 IE 和 Google chrome 中工作的临时解决方案(我的回答)..
  • @Pavel:你试过我的答案了吗?

标签: jquery html checkbox


【解决方案1】:

试试这个代码,您需要确定何时单击 DIV,然后您需要选中/取消选中该复选框。

$('.check_group').click(function (e) {
    var input = $(this).children('input[type="checkbox"]');
    //Identify the node which is clicked
    if(e.target.nodeName == "DIV")
    {
      $(input).prop('checked', !$(input).prop("checked"));
    }
    console.log($(input).is(":checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="check_group" style="background-color: rgb(200, 138, 59);">
  <input type="checkbox" />
</div>

【讨论】:

    【解决方案2】:

    你想这样做吗?

    $('.check_group').click(function () {
        var checkbox = $(this).children('input')[0];
        setTimeout(function(){alert(checkbox.checked);},200);
        //run something else
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="check_group" style="background-color: rgb(200, 138, 59);">
      <input type="checkbox" />
    </div>

    setTimeout 不是必需的,除非您想先直观地显示检查然后发出警报

    【讨论】:

    • 当我点击 Div 时,我需要更改复选框状态。 “check.checked = !check.checked;” - 这很重要。您的代码也有同样的问题,但运行速度较慢 =)
    【解决方案3】:

    临时解决方案:

    $('.check_group').click(function (e) {
        var check = $(this).children('input')[0];
        if (e.target.tagName == "INPUT") {
             check.checked = !check.checked;
        }
        check.checked = !check.checked;
        alert(check.checked);
        //
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="check_group" style="background-color: rgb(200, 138, 59);">
      <input type="checkbox" />
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      相关资源
      最近更新 更多