簡體   English   中英

如何將字母存儲在本地存儲中而不是Javascript中的點擊計數?

[英]How to store alphabets in localstorage instead of clickcount in Javascript?

我正在創建一些動態控件,並且希望從本地存儲為其分配ID。 它的工作正常,但我想代替新的數字,我希望將字母(例如A,B)分配給新創建的控件。 有可能通過javascript實現嗎?

function nextNumber() {
  if (typeof (Storage) !== "undefined") {
    if (localStorage.clickcount) {
      localStorage.clickcount = Number(localStorage.clickcount) + 1;
    } else {
      localStorage.clickcount = 1;
    }
    Increment = localStorage.clickcount;

  } else {

  }
}

elem.setAttributeNS(null, "id", "ID " + Increment)//assigning id

這是一個未經驗證的示例,您怎么做:

function nextNumber() {
  if (typeof (Storage) !== "undefined") {
    if (localStorage.clickcount) {
      var indx = localStorage.clickcount.charCodeAt(0) - 65; // Get ascii value from char
      localStorage.clickcount = String.fromCharCode(indx + 1);
    } else {
      localStorage.clickcount = "A"; // "A" has ascii value 65
    }
    Increment = localStorage.clickcount;

  } else {

  }
}

elem.setAttributeNS(null, "id", "ID " + Increment) //assigning id

基本上,您應該使用65以上的數字(這些數字表示從A開始的字符的ASCII值)。 考慮到這一點,當存儲初始計數器時,它應指向“ A”,所以它是65。當遞增時,應將該字符轉換回ASCII值,將其遞增1並轉換回字符。

您可以使用字母執行某些操作,並使用如下所示的charAt函數:

let alphab="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function nextNumber() {
  if (typeof (Storage) !== "undefined") {
    if (localStorage.clickcount) {
      localStorage.clickcount = Number(localStorage.clickcount) + 1;
    } else {
      localStorage.clickcount = 1;
    }
    Increment = localStorage.clickcount;

  } else {

  }
}

elem.setAttributeNS(null, "id", "ID " + alphab.charAt(Increment))//assigning id

但這僅限於alphab長度。 您需要為此類控件創建一個新功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM