javascript - 听复选框被选中/未选中的正确方法是什么?

标签 javascript jquery checkbox

我正在使用这段代码来检查复选框是否被选中,如果是,则在 map 上显示子菜单和特定图层:

$('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
  }
});

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

最佳答案

在您的代码中使用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.checked 将返回 true 如果检查否则 false

关于javascript - 听复选框被选中/未选中的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34398753/

相关文章:

javascript - 在react中收到消息后,Websocket立即未定义

javascript - 无法破解通过 css 插件使两个输入元素在线显示?

javascript - 为什么node.js的jQuery包中没有$.ajax方法?

python - 带有 tkinter 的很长的 list 框

javascript - Google Maps API setBounds 到精确坐标

javascript - 我的日期时间从 ASP.Net MVC 转换为 Javascript 时会转换成什么

javascript - 我想将一组 jquery 选择器存储为要延迟评估的数据结构

php - Json eval 无法解析数据

javascript - jQuery 中的价格模拟器 - 将值添加到两个变量中

php - 使用 PHP 和 MySQL 保存复选框中的数据