简体   繁体   English

Javascript使用过滤器函数中的复选框值

[英]Javascript using checkbox values in a filter function

I'm trying to make a JavaScript function that will delete all objects by using checked checkbox values and using them in my filter function. 我正在尝试创建一个JavaScript函数,它将使用选中的复选框值并在我的过滤器函数中使用它们来删除所有对象。 But I'm stuck and not sure on how I could do this? 但是我被困住了,不确定我怎么做到这一点?

I know how to get the values of the checked checkboxes but how can I use them in my filter function? 我知道如何获取已选中复选框的值,但如何在我的过滤器函数中使用它们?

function DeleteObjects() {
  var b = MyObjects.buildings;
  Object.keys(b).filter(function(e) {

    return "ALL CHECKED VALUES HERE" == b[e].type;

  }).forEach(function(i) {
    network.sendRpc({
      name: "DeleteObject",
      uid: b[i].uid
    })
  })
}
<div style="text-align:center" class="list">
  <small>building1:</small><input name="sellCB" type="checkbox" value="building1">
  <small>building2:</small><input name="sellCB" type="checkbox" value="building2">
  <small>building3:</small><input name="sellCB" type="checkbox" value="building3"><br>
  <small>building4:</small><input name="sellCB" type="checkbox" value="building4">
</div>

Place all checked values in an array and use myArray.includes(b[e].type) which will return true if your value is in the array 将所有选中的值放在数组中并使用myArray.includes(b[e].type) ,如果您的值在数组中,则返回true

Example: 例:

 var myValues =["Walls", "Doors"] var checkedValues = ["Walls"]; var filtered = checkedValues.filter(v => myValues.includes(v)); console.log(filtered) 

If i understand well you code, that would be: 如果我理解你的代码,那将是:

  function DeleteObjects() { var b = Game.currentGame.ui.buildings; Object.keys(b).filter(function(e) { const input = document.querySelector(`input[value=${b[e].type}]`); return input && input.checked; }).forEach(function(i) { Game.currentGame.network.sendRpc({ name: "DeleteObject", uid: b[i].uid }) }) } 
  <div style="text-align:center" class="list"> <small>Walls:</small><input name="sellCB" type="checkbox" value="Wall"> <small>Doors:</small><input name="sellCB" type="checkbox" value="Door"> <small>Traps:</small><input name="sellCB" type="checkbox" value="SlowTrap"><br> <small>Mines:</small><input name="sellCB" type="checkbox" value="GoldMine"> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM