帮助优化JS中的过滤结果代码

我对 PHP 开发还很陌生,使用 MySQL 并添加了 JS。我想听听专家对以下问题的意见,或者任何好的建议都可以。


因此,我正在制作一个网站,对你们大多数人来说可能很简单,但对我来说有点复杂,它允许登录用户创建活动并参加活动。


最近我添加了一个新功能 - 前端按类别过滤事件,因为我也想在 JS 上进行一些练习。还没有尝试过后端过滤。


问题是它工作正常,但我认为 JS 代码本身看起来非常糟糕和混乱。


因此我想了一个办法来优化它,但没有找到。


类别选择.html代码


<select class="custom-select mr-sm-2" id="filterCat"onchange="filterCategory()">

 <option selected>All</option>

 <option value="1">Concerts</option>

 <option value="2">Sport</option>

 <option value="3">Comedy</option>

 <option value="4">Theatre</option>

 <option value="5">Family attractions</option>

</select>

php查询以确定循环的大小


<?php

// ...

require_once('../features/con.php');

if (!$con->connect_errno) {

 $countQ = "SELECT COUNT(*) AS number FROM events;";

 $resultCounting = $con->query($countQ);

 $size = mysqli_fetch_assoc($resultCounting);

}

// ...

?>

过滤结果算法


<script type="text/javascript">

  var catinput, cat, evinput, events, table, i, t, txtValue, number, num, tableRes, none, no, tableID, tr, td;

  number = <?php echo $size['number'] ?>;


  function filterCategory() {

    catinput = document.getElementById('filterCat');

    cat = catinput.options[catinput.selectedIndex].text;

    t = "table";


    for (var j = 1; j <= number; j++) {

      num = j;

      tableRes = t.concat(num);

      none = document.getElementById(tableRes).style.display;

      if (none == "none") {

        document.getElementById(tableRes).style.display = "";

      }

    }

    }

}

</script>

每个具有不同事件的单独表都有唯一的ID,该ID是根据数据库中的event_id表列确定的(这是从1开始自动递增的列,自动设置)。


我创建了一个关联数组来列出数据库中的所有事件,然后只需添加以下一个: id="table<?php echo "$row[event_id]"?>"


但是这个 JS 代码本身 - 可以以某种方式优化吗?也许你有什么想法?


任何提示真的很感激!


温温酱
浏览 57回答 3
3回答

郎朗坤

好吧,我建议他们做很多改变。不仅是为了性能,也是为了可读性。首先,我为每个表提供了一个数据属性,稍后我们将使用该属性进行过滤。我还更改了选择框的值以匹配数据集的值。在 JS 中,我仅选择项目。您在循环的每次迭代中使用 getElementBy ,这意味着 JS 需要多次查看 DOM,我没有使用多个循环,而是将其全部编写在一个循环中。因为它可以一次性完成。最后我使用了 ES6 语法,因为它允许我使用 const 或 let< /span>解构 和 for of 循环、箭头函数、// Get the selectboxconst selectBox = document.querySelector("#filterCat");// Get all the tablesconst events = document.querySelectorAll(".event");// Add eventlistener to trigger whenever the value changesselectBox.addEventListener("change", () => {  // Get selected value  const { value } = selectBox;    // Loop over each event (table)  for(const event of events) {    // Show the table    event.style.display = "table";        // Continue to the next one if we want to show all tables    if(value === "All") continue;        // Get type from dataset    const { type } = event.dataset;    // If it is not the selected category hide it    if(value !== type) {      event.style.display = "none"    };  }});<select class="custom-select mr-sm-2" id="filterCat"> <option selected>All</option> <option value="concert">Concerts</option> <option value="sport">Sport</option> <option value="comedy">Comedy</option> <option value="theatre">Theatre</option> <option value="family-attractions">Family attractions</option></select><table class="event" data-type="concert">  <tr><td>Concert 1</td></tr></table><table class="event" data-type="sport">  <tr><td>Sport 1</td></tr></table><table class="event" data-type="comedy">  <tr><td>Comedy 1</td></tr></table><table class="event" data-type="theatre">  <tr><td>Theatre 1</td></tr></table><table class="event" data-type="family-attractions">  <tr><td>Family attractions 1</td></tr></table><table class="event" data-type="concert">  <tr><td>Concert 2</td></tr></table><table class="event" data-type="sport">  <tr><td>Sport 2</td></tr></table><table class="event" data-type="comedy">  <tr><td>Comedy 2</td></tr></table><table class="event" data-type="theatre">  <tr><td>Theatre 2</td></tr></table><table class="event" data-type="family-attractions">  <tr><td>Family attractions 2</td></tr></table>无评论版本:const selectBox = document.querySelector("#filterCat");const events = document.querySelectorAll(".event");selectBox.addEventListener("change", () => {  const { value } = selectBox;    for(const event of events) {    event.style.display = "table";        if(value === "All") continue;        const { type } = event.dataset;    if(value !== type) {      event.style.display = "none"    };  }});<select class="custom-select mr-sm-2" id="filterCat"> <option selected>All</option> <option value="concert">Concerts</option> <option value="sport">Sport</option> <option value="comedy">Comedy</option> <option value="theatre">Theatre</option> <option value="family-attractions">Family attractions</option></select><table class="event" data-type="concert">  <tr><td>Concert 1</td></tr></table><table class="event" data-type="sport">  <tr><td>Sport 1</td></tr></table><table class="event" data-type="comedy">  <tr><td>Comedy 1</td></tr></table><table class="event" data-type="theatre">  <tr><td>Theatre 1</td></tr></table><table class="event" data-type="family-attractions">  <tr><td>Family attractions 1</td></tr></table><table class="event" data-type="concert">  <tr><td>Concert 2</td></tr></table><table class="event" data-type="sport">  <tr><td>Sport 2</td></tr></table><table class="event" data-type="comedy">  <tr><td>Comedy 2</td></tr></table><table class="event" data-type="theatre">  <tr><td>Theatre 2</td></tr></table><table class="event" data-type="family-attractions">  <tr><td>Family attractions 2</td></tr></table>

婷婷同学_

这是一个更简单的实现。我使用 DIV 代替表格,以保持代码简洁。function filter_tables() {&nbsp; var selected = document.getElementById('table-selector').value;&nbsp; var tables = document.querySelectorAll('.table');&nbsp; if(selected === 'all') {&nbsp; &nbsp; tables.forEach( t => { t.className = 'table'; });&nbsp; } else {&nbsp; &nbsp; tables.forEach( t => {&nbsp; &nbsp; &nbsp; if(t.id === 'table'.concat(selected)) {&nbsp; &nbsp; &nbsp; &nbsp; t.className = 'table';&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; t.className = 'table hidden';&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; }}div.table {&nbsp;padding: 8px;&nbsp;margin: 12px;&nbsp;background-color: yellow;}div.table.hidden {&nbsp; display: none;}<select id="table-selector" onchange="filter_tables();">&nbsp; <option value="all" selected>All</option>&nbsp; <option value="1">Table 1</option>&nbsp; <option value="2">Table 2</option>&nbsp; <option value="3">Table 3</option></select><div class="table" id="table1">Table 1</div><div class="table" id="table2">Table 2</div><div class="table" id="table3">Table 3</div>

守候你守候我

var catinput, cat, evinput, events, table, i, t, txtValue, number, num, tableRes, none, no, tableID, tr, td;&nbsp; number = <?php echo $size['number'] ?>;您在脚本开头声明每个变量,但有些变量仅在函数或循环中本地使用。 仅在函数中使用的变量应在循环中声明。 在你的脚本中, num, tableRes, ... 必须在循环开始处声明 for (var j = 1; j <= number; j++) {}另外,您还可以声明一个空变量来立即填充它们。直接给出它们的值。你的脚本将像这样结束:<script type="text/javascript">&nbsp; function filterCategory() {&nbsp; &nbsp; var evinput, events, i, txtValue, number;&nbsp; &nbsp; &nbsp; &nbsp; number = <?php echo $size['number'] ?>,&nbsp; &nbsp; &nbsp; &nbsp; catinput = document.getElementById('filterCat'),&nbsp; &nbsp; &nbsp; &nbsp; cat = catinput.options[catinput.selectedIndex].text;&nbsp; &nbsp; &nbsp; &nbsp; t = "table";&nbsp; &nbsp; for (var j = 1; j <= number; j++) {&nbsp; &nbsp; &nbsp; var num = j,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tableRes = t.concat(num),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; none = document.getElementById(tableRes).style.display;&nbsp; &nbsp; &nbsp; if (none == "none") {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById(tableRes).style.display = "";&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; for (var i = 1; i <= number; i++) {&nbsp; &nbsp; &nbsp; if (cat != "All") {&nbsp; &nbsp; &nbsp; &nbsp; var no = i,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tableID = t.concat(no),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table = document.getElementById(tableID),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tr = table.getElementsByTagName("tr"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; td = tr[1].getElementsByTagName("td")[0],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; txtValue = td.innerText;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (cat.toUpperCase() != txtValue.toUpperCase()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById(tableID).style.display = "none";&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById(tableID).style.display = "";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP