After adding JSON data to an html option selector, how can I reference other data when selected?
29 观看
2回复
142 作者的声誉
I'm not sure of the proper terminology here so let me show my code:
var json = "https://example.com/";
$.getJSON(json,function(data) {
for (var x = 0; x < data.length; x++) {
$('#select').append(
'<option value="' + data[x].name + '">' + data[x].name + '</option>'
);
}
});
The JSON Data looks like the following but has much more data:
[
{
"id": "test1",
"name": "test1",
"symbol": "t1",
"rank": "1",
"price_usd": "55"
},
{
"id": "test2",
"name": "test2",
"symbol": "t2",
"rank": "2",
"price_usd": "155"
}
]
Essentially when someone uses the select option and choses "test1" I want to display the other information, such as; id, symbol, rank, etc.. What's the best way to go about this dynamically and not write a bunch of if statements?
作者: user3330820 的来源 发布者: 2017 年 12 月 27 日回应 2
1像
1773 作者的声誉
put the resulting JSON
string into an object using [JSON.parse]
1. Then you can use .toggle()
or a couple of other jQuery
fun functions and address the applicable item in the object and the values to go with.
1像
12256 作者的声誉
To get all the data in the object which you're using to populate the options (data[x].name
),
you can either filter the array of objects or change the structure so you can reference it by name,
here are some examples.
Filtering the array:
var dataXName = 'whatever name'
var obj = data.filter(function(x){ return x.name === dataXName })[0]
Mapping an object:
var byName = data.reduce(function(ac, x){
return Object.assign(ac, {[x.name]:x})
},{})
// then you can reference the object with byName['whatever name']
the solutions above are plain js and don't depend on jquery.
作者: maioman 发布者: 2017 年 12 月 27 日来自类别的问题 :
- jquery 使用JavaScript滚动溢出的DIV
- jquery 使用jQuery转义HTML字符串
- jquery 如何将html实体与jQuery进行比较
- jquery jQuery是否存在“存在”功能?
- jquery How do you remove all the options of a select box and then add one option and select it with jQuery?
- jquery 获取触发事件的元素的ID
- html 如何检测网页中使用了哪一个定义的字体?
- html 如何为我的网站提供iPhone的图标?
- html 如何在Web表单字段/输入标记上禁用浏览器自动完成?
- html 如何使用Prototype自动调整textarea?
- html 如何定制有序列表中的数字?
- json Safely turning a JSON string into an object
- json 如何在Ruby on Rails中“漂亮”格式化我的JSON输出?
- json 在jQuery中序列化为JSON
- json 你能在JSON对象中使用尾随逗号吗?
- json Can comments be used in JSON?
- json 我可以用JSON提供RSS吗?