从JSON插入HTML选择标签选项 [英] Insert into HTML select tag options from a JSON
问题描述
这就是问题所在:我在我的Web应用程序中的localStorage中保存了一个JSON对象.
在页面加载时,此JSON使用JSON.stringify
保存为字符串,位于我的一个函数中:
So, here's the deal: I have a JSON object saved in my web App at localStorage.
This JSON is being saved as a string, with JSON.stringify
, inside one of my functions, on the page load:
localStorage.setItem("MyData", JSON.stringify(data));
数据保存如下:
[{"NAMEVAR":"Some Data 1","CODE":"1"},{"NAMEVAR":"Some Data 2","CODE":"2"}]
数据是请求的结果.数据已成功保存在主页上,因此以后可以使用.之后,我必须使用从数据中获取的内容在另一页上加载表单.
data is the result from a request. The data is being saved successfully at the home page, so i could use later. After that, i have to load up a form on another page, using what i got from data.
我在页面上有这个选择标签:
I have this select tag on the page:
<select id="mySelectID" name="select" class="main-form">
<option value="">None Selected</option>
</select>
我想做的很简单:我正在使用 json2html 将项目从数据,并且选项值具有来自数据的CODE. 因此,我期望发生的事情是:
What i want to do is simple: I'm using json2html to add items to this select tag from the data, and the option value has the CODE from data. So, what i expected to happen is:
<select id="mySelectID" name="select" class="main-form">
<option value="1">Some Data 1</option>
<option value="2">Some Data 2</option>
</select>
这样做:
var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var transform = {tag:'option', id:'.CODE',html:'{$NAMEVAR}'};
document.getElementById('mySelectID').innerHtml = json2html.transform(jsonData,transform);
但是这行不通,我知道行不通.问题是我不知道如何将此JSON插入HTML选项中.我以为json2html可以帮到我,但是由于我不会说英语,所以有点难以理解,而且我对JavaScript还是陌生的.
But this does not work, and i know it won't. The problem is that i do not know how to insert this JSON into options to my HTML. I thought that json2html could help me, but as i do not speak English natively, it's kinda of being hard for me to understand that, and I'm also new to JavaScript.
谢谢!
推荐答案
您不需要为此进行转换,请尝试以下方式:
You don't need the transform for this, try it this way:
var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var $select = $('#mySelectID');
$(jsonData).each(function (index, o) {
var $option = $("<option/>").attr("value", o.CODE).text(o.NAMEVAR);
$select.append($option);
});
这是一个正常工作的小提琴.
这篇关于从JSON插入HTML选择标签选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!