我想知道是否有办法获取选中的复选框的值,而不是使用DeleteObject函数中filter函数中的值。
<div style="text-align:center" class="list">
<small>Walls:</small><input id="deleteCheckbox" type="checkbox" value="Wall">
<small>Doors:</small><input id="deleteCheckbox" type="checkbox" value="Door">
<small>Traps:</small><input id="deleteCheckbox" type="checkbox" value="SlowTrap"><br>
<small>Mines:</small><input id="deleteCheckbox" type="checkbox" value="GoldMine">
</div>
Javascript:
function DeleteObject() {
var b = Game.currentGame.ui.buildings;
Object.keys(b).filter(function(e) {
return CheckBoxValuesHere == b[e].type;
}).forEach(function(i) {
Game.currentGame.network.sendRpc({
name: "DeleteObject",
uid: b[i].uid
})
})
}
答案 0 :(得分:2)
如评论中所述,id's
应该是唯一的。要获取已选中复选框的值,请将change
事件添加到类型为checkbox
的输入中,然后使用已选中复选框捕获输入。
document.querySelectorAll('input[type="checkbox"]')
.forEach(input => {
input.addEventListener('change', function() {
const values = [...document.querySelectorAll('input:checked')].map(input => input.value);
console.log(values);
});
});
<div style="text-align:center" class="list">
<small>Walls:</small><input id="deleteCheckbox" type="checkbox" value="Wall">
<small>Doors:</small><input id="deleteCheckbox" type="checkbox" value="Door">
<small>Traps:</small><input id="deleteCheckbox" type="checkbox" value="SlowTrap"><br>
<small>Mines:</small><input id="deleteCheckbox" type="checkbox" value="GoldMine">
</div>
答案 1 :(得分:1)
function getItemsToDelete() {
// get a nodeList of all selected elements,
// convert it to an array and return an
// array of the values.
return Array.from(
document.querySelectorAll(
'input[name=deleteCheckbox]:checked'
)
).map( item => item.value );
}
console.log(getItemsToDelete());
<ul style="list-style:none">
<li><input name="deleteCheckbox" type="checkbox" value="Wall"><small>Walls</small></li>
<li><input name="deleteCheckbox" type="checkbox" value="Door" checked><small>Doors</small></li>
<li><input name="deleteCheckbox" type="checkbox" value="SlowTrap"><small>Traps</small></li>
<li><input name="deleteCheckbox" type="checkbox" value="GoldMine"><small>Mines</small></li>
</ul>
答案 2 :(得分:0)
为每个复选框添加唯一的名称或ID,并将它们的侦听器分配给click
事件(在JS代码中)或直接在HTML中。然后在JS中使用document.getElementById(<ID>).value
引用复选框值。