检索表单值以JSON字符串形式发送到localStorage的最简单方法是什么?我用for循环开始了一个函数,但是被卡住了。任何微调都非常感谢(对此还是很新的)请不要使用JQuery。谢谢

 <input type="submit" name="submit" value="submitOrder" onclick="return getValues();">

var userOrder='';
function getValues(){
    for(var i=0; i < document.forms[0].length - 1; i++){
        console.log(document.forms[0][i]);
        return false;
    }
}

localStorage.setItem('userOrder',JSON.stringify(userOrder));
console.log(localStorage.getItem('userOrder'));

最佳答案

您可以这样做:

html:

<form id="myform">
  <input type="text" name="test">
  <input type="submit" value="submitOrder">
</form>

js:
const userOrder = {};

function getValues(e) {
  // turn form elements object into an array
  const elements = Array.prototype.slice.call(e.target.elements);

  // go over the array storing input name & value pairs
  elements.forEach((el) => {
    if (el.type !== "submit") {
      userOrder[el.name] = el.value;
    }
  });

  // finally save to localStorage
  localStorage.setItem('userOrder', JSON.stringify(userOrder));
}

document.getElementById("myform").addEventListener("submit", getValues);

09-25 19:00