【问题标题】:How can I store options tags in sessionStorage?如何在 sessionStorage 中存储选项标签?
【发布时间】:2017-06-23 21:45:28
【问题描述】:

这是我的 HTML:

<select>
   <option value="val1">Text1</option>
   <option value="val2">Text2</option>
   <option value="val3">Text3</option>
   <option value="val4">Text4</option>
</select>

它正在通过$.ajax()动态填充

我需要创建一个函数,将 key 中的 "val"sessionStorage 中的“value”中的 Text 作为对象引用。我怎样才能做到这一点?

如何通过index进行迭代?

我的尝试:

document.getElementsByClassName('next')[0].addEventListener('click', function() {
    sessionStorage.setItem(option.value, option.innerText);
});

.addEventListener() 根本没有开火。 . .为什么?

另外,我需要之后加载它。我该怎么做?我使用.trigger()吗?

【问题讨论】:

  • 你能告诉我们你到目前为止尝试过的代码吗?
  • 好的,请稍等。
  • 你去,编辑...请帮助。

标签: javascript jquery html ajax session-storage


【解决方案1】:

就像这样:

var btn = document.querySelector(".next");
var test = document.querySelector(".test");

btn.addEventListener("click", function(){
  // Get a reference to the select's options
  var options = document.querySelectorAll("option");

  // Loop through the options and store the value and text in sessionStorage:
  for(var i = 0; i < options.length; ++i){
    sessionStorage.setItem(options[i].getAttribute("value"), options[i].textContent);
  }
});

test.addEventListener("click", function(){

  // Now, just to show how to get the values out of sessionStorage:
  for (var i = 0; i < sessionStorage.length; i++){
    alert(sessionStorage.getItem(sessionStorage.key(i)));
  }

});
<select>
   <option value="val1">Text1</option>
   <option value="val2">Text2</option>
   <option value="val3">Text3</option>
   <option value="val4">Text4</option>
</select>
<button class="next">Next</button>

<button class="test">Test</button>

此代码在 Stack Overflow sn-p 环境中不起作用,但您可以看到它在 here 工作。

【讨论】:

  • 没问题。只需将我的“设置”代码包装在一个函数中。我会更新我的答案。
  • @tholo 查看我更新的答案,通过单击按钮设置数据并通过单击不同的按钮将其取回。
  • 请稍等。谢谢老兄。
  • @tholo 要取回值,只需将事件绑定更改为window.addEventListener("DOMContentLoaded, function(){....}");,但使用我相同的函数代码。您的 .addEventListener 似乎会触发 OK(假设您在将 .next 按钮解析到内存之后拥有该代码),但侦听器中的代码不会做任何事情,因为 option.value 本身具有没有意义。
  • @tholo 嗯,还有其他方法(options[i].attributes[0].value),不过这些方法和你说的JQuery方法差不多。
猜你喜欢
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
相关资源
最近更新 更多