听取/取消选中复选框的正确方法是什么?

时间:2015-12-21 15:07:38

标签: javascript jquery checkbox

我使用此代码,检查复选框是否已选中,如果是,请在地图上显示子菜单和特定图层:

$('input').on('change', function () {
  var x = $( 'input:checked' ).val(); // x gets the value attribute of changed checkbox
  if ($('input').is(':checked')) {
    sublayers.getSubLayer(x).show(); // shows specified layer on the map
    $('#' + x).show(); // shows id targeted submenu under the checked checkbox
  } else {
    sublayers.getSubLayer(x).hide(); // hides sublayer on the map if unchecked
    $('#' + x).hide();  // hides specific submenu
  }
});

所以会发生的情况是第一个复选框工作正常,并且以下复选框不响应。更重要的是,如果我开始检查从底部到顶部的复选框,它们可以工作,但显示适合上面一个复选框的子图层。也取消选中不会触发任何内容。

3 个答案:

答案 0 :(得分:3)

使用this获取代码中已点击复选框的上下文。

 $('input[type="checkbox"]').on('change', function (){
            var x = this.value; // x gets the value attribute of changed checkbox
            if (this.checked){
                sublayers.getSubLayer(x).show(); // shows specified layer on the map
                $('#' + x).show(); // shows id targeted submenu under the checked checkbox
            }
            else {
                sublayers.getSubLayer(x).hide(); // hides sublayer on the map if unchecked
                $('#' + x).hide();  // hides specific submenu
            }
    });

如果选中其他this.checkedtrue将返回false

答案 1 :(得分:1)

使用$(this)代替$('input')

$('input').on('change', function (){
    var x = $(this).val(); // x gets the value attribute of changed checkbox

    if ( $( this ).is(':checked')){
        sublayers.getSubLayer(x).show(); // shows specified layer on the map
        $('#' + x).show(); // shows id targeted submenu under the checked checkbox
    }
    else {
        sublayers.getSubLayer(x).hide(); // hides sublayer on the map if unchecked
        $('#' + x).hide();  // hides specific submenu
    }
});

答案 2 :(得分:1)

使用this代替'input:checked'

在回调中,context设置为触发事件的元素。因此,当change事件发生并且调用回调时,this中存储了元素。您可以使用$(this).is(":checked")

轻松确定是否选中了新的复​​选框状态