Коды клавиши для клавиш со стрелками

Вы можете использовать локальное хранилище для хранения пары ключ / значение.

Пары ключ / значение будут оставаться в браузере до тех пор, пока вы не удалите их (т.е. с помощью localStorage.clear()).

Вот идея о том, как вы могли бы использовать его в своем проекте.

  1. Каждый раз, когда пользователь изменяет поле ввода количества (не сохраняя его), вы сохраняете значение в локальном хранилище.
  2. Для этого вам нужно добавить уникальный атрибут id в каждое поле ввода количества, например, id="Qty1056". (1056 код товара). Затем, прежде чем установить для атрибута «значение» значение 0 (например, quantityField.setAttribute('value', '0');), вы проверяете локальное хранилище, чтобы увидеть, сохранено ли там значение с момента последнего изменения пользователем количества для этого элемента. (Если в локальном хранилище нет значения, установите значение количества в 0. Если значение существует в локальном хранилище для этого кода изделия, получите значение и установите для него значение поля ввода количества.)

Я добавил мой новый код в ваш полный код. Код, который я добавил, помечен комментарием //ADDING NEW CODE и другими комментариями.

Кроме того, вы можете проверить, что в localStorage, посетив вкладку Application в Developer tools (я прикрепил скриншот ниже кода).

$(document).ready(function() {
  //clear local storage. (Note: if you want the values to persist after u refresh browser then you should NOT clear local storage).
  localStorage.clear();
  //the rest of your (document).ready code goes here as normal
});

//Your addTable function. (It's mostly the same as you had. I've added comments where i've added code)
function addTable(tableData) {
  var col = Object.keys(tableData[0]);
  var countNum = col.filter(i => !isNaN(i)).length;
  var num = col.splice(0, countNum);
  col = col.concat(num);
  var table = document.createElement("table");
  var tr = table.insertRow(-1); // TABLE ROW.
  var colNum = col.length; //to improve the speed
  for (var i = 0; i < colNum + 1; i++) {
    var th = document.createElement("th"); // TABLE HEADER.
    if (i >= colNum) {
      th.innerHTML = "Quantity";
      tr.appendChild(th);
      tr.classList.add("text-center");
      tr.classList.add("head")
    } else {
      th.innerHTML = col[i];
      tr.appendChild(th);
      tr.classList.add("text-center");
      tr.classList.add("head")
    }
  }
  for (var i = 0; i < tableData.length; i++) {
    tr = table.insertRow(-1);
    for (var j = 0; j < col.length + 1; j++) {
      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input");
      hiddenField.style.display = "none";
      var tabledata = tableData[i][col[j]];
      if (i > -1 && j >= colNum) {

        var quantityField = document.createElement("input");
        quantityField.style.border = "none";
        quantityField.style["text-align"] = "center";
        quantityField.setAttribute('name', 'Quantity');
        quantityField.setAttribute('autocomplete', 'on');
        quantityField.setAttribute('type', 'number');
        quantityField.setAttribute('required', 'required');
        quantityField.classList.add("dataReset");

        //ADDING CODE HERE
        //create a unique Id string for the quantity input field.
        //We will use a string e.g 'Qty' concantenated with the item code for this item (as it is unique).
        //So we will have something like 'Qty1056'
        var quantityIdString = 'Qty' + tableData[i]['Item Code'];
        //add the id attribute to the input field
        quantityField.setAttribute('id', quantityIdString);
        //check localStorage to see if a quantity value exists for this item code
        //the key will be something like 'Qty1056' (the same as the id of the quantity input field).
        if(localStorage.getItem(quantityIdString) === null){
          //this key does NOT exist in local storage 
          //therefore the user has not changed the value of this items quantity input field yet so set it to 0.
          quantityField.setAttribute('value', '0');
        }else{
          //this key DOES exist in local storage so get the value from local storage and 
          //set the value attribute of our quantity input field to it
          var quantityFromLocalStorage = localStorage.getItem(quantityIdString);  
          quantityField.setAttribute('value', quantityFromLocalStorage);    
        }
        //append the quantity field to the table cell
        tabCell.appendChild(quantityField);     
      } else {
        if (tableData[i]['Item Code'] === tableData[i][col[j]]) {
          tabCell.innerHTML = tabledata;
          hiddenField.setAttribute('name', 'Item_Code');
          hiddenField.setAttribute('value', tabledata);
          tabCell.appendChild(hiddenField);
        }
        if (tableData[i]['Item Name'] === tableData[i][col[j]]) {
          tabCell.innerHTML = tabledata;
          hiddenField.setAttribute('name', 'Item_Name');
          hiddenField.setAttribute('value', tabledata);
          tabCell.appendChild(hiddenField);
        }
        if (j > 1)
          tabCell.classList.add("text-right");
      }
    }
  }

  var divContainer = document.getElementById("HourlysalesSummary");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");
  //ADDING CODE HERE
  //Now that the table has been appended to the document we can add the listeners to the quantity input fields as follows.
  for (var i = 0; i < tableData.length; i++) {
    ///log the item code to check it
    console.log(tableData[i]['Item Code']);
    //pass in the item code to the addQuantityFieldListener function
    addQuantityFieldListener(tableData[i]['Item Code']);
  }
}

//ADDING CODE HERE
function addQuantityFieldListener(itemCode){
  /* This function adds an "input" listener to a quantity input field to check when a new quantity value 
   * is selected/entered by the user for a particular item.
   * Each time a new quantity is selected/entered we store the new value in local storage. 
   */
  //form the quantityIdString which will also be the key of the item in local storage
  var quantityIdString = 'Qty' + itemCode;
  var quantityInputField = document.getElementById(quantityIdString);
  //we listen for the "input" event which will occur when a new quantity value is selected/entered by the user on this quantity input field. 
  quantityInputField.addEventListener("input", function(){
      //store the most recent quantity value for this item in local storage as follows:
      localStorage.setItem(quantityIdString, quantityInputField.value);
  });
}

Снимок экрана с вкладкой "Приложение" в инструментах разработчика (с указанием пар ключ / значение локального хранилища)

enter image description here

5
задан JoshBerke 1 December 2008 в 06:07
поделиться

2 ответа

Вы имеете в виду событие KeyUp? KeyPress не становится уволенным за Стрелки, и событие args не имеет свойства KeyCode, но для Клавиш со стрелками в keyUp событии они:

Ключи. Ключи. Вниз, ключи. Левый, Keys.right

12
ответ дан 18 December 2019 в 10:49
поделиться

http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx

Ключи. Ключи. Левый, ключи. Право, ключи. Вниз.

4
ответ дан 18 December 2019 в 10:49
поделиться
Другие вопросы по тегам:

Похожие вопросы: