亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

幫助優化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 關注
  • 176 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號