js處理枚舉


js處理枚舉

標簽(空格分隔): javascript enum


Backgroud: DB中讀到的status 是 int類型,並且做了pagination,不太好單獨拎出來這個字段做枚舉轉換,於是考慮用js在前端做個簡單處理。

  1. 采用const方式定義;
  2. 通過value 獲取key,或者通過key獲取value;
  3. 定位獲取頁面上每條數據的status cell;
  4. 獲取每個cell中的值,是DB中的int類型;
  5. 通過cell中拿到的int 數據,即value,拿到const中對應的key,並回寫到該cell;

1.定義

<script>
    const Status = {
        IDLE:0,
        INUSE:1,
        DOWN:2
    }
</script>

補充: let 聲明的變量可以被更改,重新賦值; const 聲明的變量,指向memory addr,不可重新賦值;

2. 理解針對Status 的各種操作

  1. console.log(Object.keys(ClientStatus)[0]) --->'IDEL'
  2. console.log(Object.keys(ClientStatus)) ---> ['IDLE','INUSE','DOWN']
  3. console.log(ClientStatus.DOWN.valueOf()) ---> 2
  4. console.log(ClientStatus.DOWN) ----> 2
  5. console.log(ClientStatus.hasOwnProperty('IDLE')) ---> true
  6. console.log(ClientStatus.propertyIsEnumerable('IDLE')) ---> true

3. 定位table中每條數據的status cell

  1. 定位cell:let per_status = document.getElementById(cellid)
  2. 定位每個 cell:cell-->td 的parent是 tr
 $("tr[id=trid]").each(function (index, element){
    let cstatus = document.getElementById(cellid);
    })
  1. 但是如果要重寫每個cell_status,那么每個cell_status的id都要不同,這樣才不會把相同數據寫入不同的cell中。
    那就把cjid 當做cell_status的 td_id(這部分要在html中定義好)。
# html
<td>{{ jid }}</td>
<td id={{ jid }}>{{ status }}</td>

#script
 $("tr[id=clientlist]").each(function (index, element){
    let cjid = $(element).children('td')[0].innerHTML;
    let cstatus = document.getElementById(cjid);
    })

4. 獲取每個cell中的值,是DB中的int類顯示在html中,我們需要把這個int型轉為humanized

let ss = $(element).children('td')[1].innerHTML; --> 0,1,2

5. 通過cell中拿到的int數據,即value,拿到const中對應的key,並回寫到該cell;

# html
<td>{{ jid }}</td>
<td id={{ jid }}>{{ status }}</td>

#script
 $("tr[id=clientlist]").each(function (index, element){
    let cjid = $(element).children('td')[0].innerHTML;
    let cstatus = document.getElementById(cjid);
    let ss = $(element).children('td')[1].innerHTML; #0,1,2
    let upStatus = Object.keys(ClientStatus)[ss]; # IDLE, INUSE, DOWN
    cstatus.innerText = upStatus; # 將upStatus回寫入html頁面對應的td中。
    })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM