为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
温温酱 2023-12-15 15:58:13
我对 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 代码本身 - 可以以某种方式优化吗?也许你有什么想法?任何提示真的很感激!
查看完整描述

3 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

好吧,我建议他们做很多改变。不仅是为了性能,也是为了可读性。

首先,我为每个表提供了一个数据属性,稍后我们将使用该属性进行过滤。我还更改了选择框的值以匹配数据集的值。

在 JS 中,我仅选择项目。您在循环的每次迭代中使用 getElementBy ,这意味着 JS 需要多次查看 DOM,我没有使用多个循环,而是将其全部编写在一个循环中。因为它可以一次性完成。

最后我使用了 ES6 语法,因为它允许我使用 const 或 let< /span>解构 和 for of 循环、箭头函数、

// Get the selectbox

const selectBox = document.querySelector("#filterCat");

// Get all the tables

const events = document.querySelectorAll(".event");


// Add eventlistener to trigger whenever the value changes

selectBox.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>


查看完整回答
反对 回复 2023-12-15
?
婷婷同学_

TA贡献1844条经验 获得超8个赞

这是一个更简单的实现。我使用 DIV 代替表格,以保持代码简洁。


function filter_tables() {

  var selected = document.getElementById('table-selector').value;

  var tables = document.querySelectorAll('.table');

  if(selected === 'all') {

    tables.forEach( t => { t.className = 'table'; });

  } else {

    tables.forEach( t => {

      if(t.id === 'table'.concat(selected)) {

        t.className = 'table';

      } else {

        t.className = 'table hidden';

      }

    });

  }

}

div.table {

 padding: 8px;

 margin: 12px;

 background-color: yellow;

}

div.table.hidden {

  display: none;

}

<select id="table-selector" onchange="filter_tables();">

  <option value="all" selected>All</option>

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

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

  <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>


查看完整回答
反对 回复 2023-12-15
?
守候你守候我

TA贡献1802条经验 获得超10个赞

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

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

您在脚本开头声明每个变量,但有些变量仅在函数或循环中本地使用。 仅在函数中使用的变量应在循环中声明。 在你的脚本中, num, tableRes, ... 必须在循环开始处声明 for (var j = 1; j <= number; j++) {}


另外,您还可以声明一个空变量来立即填充它们。直接给出它们的值。


你的脚本将像这样结束:


<script type="text/javascript">

  function filterCategory() {

    var evinput, events, i, txtValue, number;

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

        catinput = document.getElementById('filterCat'),

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

        t = "table";


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

      var num = j,

          tableRes = t.concat(num),

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


      if (none == "none") {

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

      }

    }


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

      if (cat != "All") {

        var no = i,

            tableID = t.concat(no),

            table = document.getElementById(tableID),

            tr = table.getElementsByTagName("tr"),

            td = tr[1].getElementsByTagName("td")[0],

            txtValue = td.innerText;

            

        if (cat.toUpperCase() != txtValue.toUpperCase()) {

          document.getElementById(tableID).style.display = "none";

        } else {

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

        }

      }

    }

  }

</script>


查看完整回答
反对 回复 2023-12-15
  • 3 回答
  • 0 关注
  • 56 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信