Javascript函数:复选框选中时不发出警报
当我选中复选框时,我试图找出为什么警报框和控制台日志不能按预期工作 JSFIDDLE: HTML:Javascript函数:复选框选中时不发出警报,javascript,jquery,mapbox,Javascript,Jquery,Mapbox,当我选中复选框时,我试图找出为什么警报框和控制台日志不能按预期工作 JSFIDDLE: HTML: 一个 两个 三 JAVASCRIPT: var featureLayer = L.mapbox.featureLayer() .loadURL('/URL/path/to/geojson/data/') .addTo(map) .setFilter(showIfChecked); $("input[type='checkbox']").click(function()
一个
两个
三
JAVASCRIPT:
var featureLayer = L.mapbox.featureLayer()
.loadURL('/URL/path/to/geojson/data/')
.addTo(map)
.setFilter(showIfChecked);
$("input[type='checkbox']").click(function() {
showIfChecked();
});
function showIfChecked(feature) {
var parameter_codes = [1,2,3,4,5];
for (var i = 0; i < parameter_codes.length; i++) {
if ($("#"+parameter_codes[i]).prop("checked")) {
console.log(this); //shouldn't this return something like "#2" if the second checkbox is checked?
return (feature.properties["property"] === parameter_codes[i]);
} else {
return false;
}
}
}
var featureLayer=L.mapbox.featureLayer()
.loadURL('/URL/path/to/geojson/data/'))
.addTo(地图)
.setFilter(显示已选中);
$(“输入[type='checkbox'])。单击(函数(){
showIfChecked();
});
功能showIfChecked(功能){
var参数_代码=[1,2,3,4,5];
对于(变量i=0;i
有两个问题:首先,当一个项目不匹配时,您就要退出循环。因此,如果选中了#2
,则检查#1
,查看它是否未选中,并立即返回false
相反,仅在选中所有选项后返回:
for (var i = 0; i < parameter_codes.length; i++) {
if ($("#"+parameter_codes[i]).prop("checked")) {
console.log(this); //shouldn't this return something like "#2" if the second checkbox is checked?
return (feature.properties["property"] === parameter_codes[i]);
}
}
return false;
照原样,由于您正在查看功能
参数,但您没有在调用中传递该参数,因此此代码仍然会爆炸
showIfChecked();
// ...
function showIfChecked(feature) {
// ...
return (feature.properties["property"] === parameter_codes[i]);
以下是我的代码版本: 我传入了一个对复选框的引用,该复选框单击到
showIfChecked
方法
$("input[type='checkbox']").click(function() {
showIfChecked();
});
到
然后,我只是使用传入的特性/复选框作为jQuery对象来获取id属性
alert($(feature.attr('id'))代码>您想要实现什么?您的代码似乎有点复杂
如果只需要使用给定元素中的数据调用函数,可以直接将其传递给showIfChecked
function showIfChecked(id) {
console.log(id);
}
$("input[type='checkbox']").click(function(event) {
if ($(event.currentTarget).prop("checked")) {
showIfChecked((event.currentTarget.id));
}
});
更改单击
至更改
$("input[type='checkbox']").click(function() {
showIfChecked();
});
$("input[type='checkbox']").click(function() {
showIfChecked(this); // this refers to the checkbox element clicked
});
function showIfChecked(id) {
console.log(id);
}
$("input[type='checkbox']").click(function(event) {
if ($(event.currentTarget).prop("checked")) {
showIfChecked((event.currentTarget.id));
}
});