如何提取字符串形式的属性值,并在其上循环

q9rjltbz  于 2021-09-29  发布在  Java
关注(0)|答案(2)|浏览(332)

我正在练习dom操作,创建过滤器并组合它们。
我有一个类似于下面的对象数组,其中有一些属性(如果我没有使用正确的tearms,很抱歉…),比如 data.team 它可以包含一个字符串,该字符串包含多个由逗号分隔的值。
现在,复选框过滤器仅在 data.cars 只有一个值。我如何处理它们,所以当我点击 Ferrari 我让所有的球员都拥有那辆车,而不仅仅是只有那辆车的球员??
到目前为止我已经试过了 split 看起来很有希望……但我找不到办法让它发挥作用

let moreCars = []
justTeams = data[i].cars
justTeams.split(",");
moreCars.push(justTeams.split(","));
console.log(moreCars[0])

这是我代码的精简复制。我希望它不会太混乱。

let data = [{
    player: "Cristiano Ronaldo",
    team: "Juventus",
    cars: "Bugatti, Ferrari, Aston Martin, Porsche",
  },
  {
    player: "Leo Messi",
    team: "Barcelona",
    cars: "Ferrari,Porsche, Audi",
  },
  {
    player: "Neymar",
    team: "Barcelona",
    cars: "Ferrari",
  },
  {
    player: "Mbappe",
    team: "PSG",
    cars: "Audi",
  },
]

function loadFunctions(data) {
  createTable(data);
  dropdown(data);
  setEventListeners(data)
}
loadFunctions(data)

// Create Table // 
function createTable(data) {
  const tBody = document.getElementById('table-data');
  tBody.innerHTML = ''

  for (i = 0; i < data.length; i++) {
    let row = document.createElement('tr');

    let tdName = document.createElement('td');
    let tdTeam = document.createElement('td');
    let tdCars = document.createElement('td');

    tdName.innerHTML = data[i].player;
    tdTeam.innerHTML = data[i].team;
    tdCars.innerHTML = data[i].cars;

    tBody.appendChild(row);

    row.appendChild(tdName);
    row.appendChild(tdTeam);
    row.appendChild(tdCars);
  }
}

// DROPDOWN

function dropdown(data) {
  let selectTeam = document.getElementById('team')
  var teamsArray = [];

  for (var a = 0; a < data.length; a++) {
    var allTeams = data[a].team;
    teamsArray.push(allTeams);
  }
  for (var a = 0; a < teamsArray.length; a++) {
    var option = document.createElement('option')
    option.innerHTML = teamsArray[a];
    option.value = teamsArray[a];
    selectTeam.appendChild(option)
  }
}

function setEventListeners(data) {

  let playerTeam = document.getElementById('team').addEventListener('change', (event) => {
    checkbox(data)
  });
  console.log(playerTeam)
  let checkBoxes = document.querySelectorAll('input[type=checkbox][name=car]');
  Array.from(checkBoxes).forEach(function(oneCheckBox) {
    oneCheckBox.addEventListener('change', function() {
      checkbox(data);
    })
  })
}

function checkbox(data) {
  let playerTeam = document.querySelector("#team").value;

  let checkBoxes = document.querySelectorAll('input[type=checkbox][name=car]');
  let optionChecked = [];

  checkBoxes.forEach(function(oneCheckBox) {

    optionChecked =
      Array.from(checkBoxes) //convert to array to filter and map
      .filter(i => i.checked) // use array.filter to remove unchecked ones
      .map(i => i.value) // use array.map to extract checked values
    console.log(optionChecked)
  })
  filtering(data, optionChecked, playerTeam)
}

function filtering(data, optionChecked, playerTeam) {

  let filteredResults = [];
  if (optionChecked.length === 0 && playerTeam === 'all') {
    filteredResults = data
  } else if (optionChecked.length === 0 && playerTeam != 'all') {
    for (let i = 0; i < data.length; i++) {
      if (data[i].team == playerTeam) {
        filteredResults.push(data[i]);
      }
    }
  } else if (optionChecked.length != 0 && playerTeam === 'all') {
    for (let i = 0; i < data.length; i++) {
      if (optionChecked.includes(data[i].cars)) {
        filteredResults.push(data[i]);
      }
    }
  } else {
    for (let i = 0; i < data.length; i++) {
      if (optionChecked.includes(data[i].cars) && data[i].team == playerTeam) {
        filteredResults.push(data[i]);
      }
    }
  }
  createTable(filteredResults)
}
<body>

  <h2 style="color: brown;">Football players and Fancy cars</h2>
  <!--checkboxes and dropdown -->
  <div>
    <div>
      <form class=form>
        <p>Filter by car</p>
        <label><input type="checkbox" name="car" value="Bugatti" id="bu">Bugatti</label>
        <label><input type="checkbox" name="car" value="Ferrari" id="fe">Ferrari</label>
        <label><input type="checkbox" name="car" value="Aston Martin" id="as">Aston Martin</label>
        <label><input type="checkbox" name="car" value="Porsche" id="pors">Porsche</label>
        <label><input type="checkbox" name="car" value="Audi" id="Au">Audi</label>
      </form>
    </div>
    <div>
      <p>Filter by team:</p>
      <select name="equipo" class="alltypes" id="team">
        <option value="all">All</option>

      </select>
    </div>
    <!-- Table  -->
    <table style="width: 100%" class="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>equipo</th>
          <th>Cars</th>
        </tr>
      </thead>
      <tbody id="table-data">
        <!-- JS generated Table goes here -->
      </tbody>
    </table>
  </div>
  <!-- end Table -->
  <script src="main.js"></script>

</body>
oewdyzsn

oewdyzsn1#

if (optionChecked.includes(data[i].cars)) {
    filteredResults.push(data[i]);
}

应改为:

if (data[i].cars.includes(optionChecked)) {
    filteredResults.push(data[i]);
}

你应该检查一下,如果 optionChecked 存在于 data[i].cars 反之亦然。
但我认为你的算法有问题,因为你想如何处理多个选中的复选框?!
更新
你可以检查一下 data[i].cars 以这种方式选中了所有选项:

if (optionChecked.length != 0 && playerTeam === 'all') {
    for (let i = 0; i < data.length; i++) {
      shouldAdd = true;
      optionChecked.forEach((option) => {
        if (!data[i].cars.includes(option)) {
          shouldAdd = false;
        }
      })
      if (shouldAdd) {
        filteredResults.push(data[i]);
      }
    }

笔记
您有一个打字错误(布加迪),请参见以下内容: <label><input type="checkbox" name="car" value="Buggatti" id="bu">Bugatti</label> {球员:“克里斯蒂亚诺·罗纳尔多”,球队:“尤文图斯”,汽车:“布加蒂,法拉利,阿斯顿·马丁,保时捷”,

gywdnpxw

gywdnpxw2#

很抱歉,我根本不懂你的代码,但这可能对你有帮助!

<body>
<style>* { font-family: sans-serif; }</style>
<div class="filter">
    <h1>Select Player</h1>
    <div class="checkbox">
        <label><input type="radio" name="radio" onchange="filterData(this)" value="0"/>Cristiano Ronaldo</label>
        <label><input type="radio" name="radio" onchange="filterData(this)" value="1"/>Leo Messi</label>
        <label><input type="radio" name="radio" onchange="filterData(this)" value="2"/>Neymar</label>
    </div>

    <div id="result">
    </div>

<script src="script.js"></script>
</body>
var data = [{
    player: "Cristiano Ronaldo",
    team: "Juventus",
    cars: "Buggati, Ferrari, Aston Martin, Porsche"
},
    {
    player: "Leo Messi",
    team: "Barcelona",
    cars: "Ferrari, Porsche, Audi",
},
    {
    player: "Neymar",
    team: "Barcelona",
    cars: "Ferrari"
}];

function filterData(t) {
    if (!t.checked) return;

    index = parseInt(t.value);
    result = document.getElementById("result");

    elem1 = document.createElement("h1")
    elem2 = document.createElement("h2")
    elem3 = document.createElement("h3")

    elem1.innerText = data[index].player;
    elem2.innerText = data[index].team;
    elem3.innerText = data[index].cars;
    result.innerHTML = '';
    result.appendChild(elem1);
    result.appendChild(elem2);
    result.appendChild(elem3);
}

也许这对你有帮助!

相关问题