我正在使用这段代码来检查复选框是否被选中,如果是,则在 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/