【问题标题】:How to do an HTML select form where the selected option update a JSON value?如何在所选选项更新 JSON 值的情况下执行 HTML 选择表单?
【发布时间】:2013-09-11 12:33:36
【问题描述】:

我目前有一个 HTML+JS 网页,我在其中硬编码起始条件(一个国家的西、北、东、南地理坐标):

var WNES = { "W": 67.0, "N":37.5, "E": 99.0, "S": 5.0, "item":"India" };

不过,我只收集了大约 180 个国家/地区的数据,所以我也有:

var WSEN_list = [
    {"W":60.504050405040545;"S":29.306134923492337;"E":75.1575157515752;"N":38.47551472547255;"item":"Afghanistan"},
    {"W":11.611161116111646;"S":-17.94743030603061;"E":24.068406840684105;"N":-4.453854347434742;"item":"Angola"},
    {"W":19.279927992799315;"S":39.62168720072006;"E":21.00810081008106;"N":42.67814713471347;"item":"Albania"},
    {...}
];

我希望我的最终用户使用 html <select> 元素选择一个国家/地区:

<form>
Select your country:
<select id="mySelect">
  <option>Afghanistan</option>
  <option>Albania</option>
  <option>Angola</option>
</select>
</form>

然后,存储用户选择的项目值(例如“安哥拉”),所以我可以使用这个键来搜索我的数据和状态列表:

var WNES = {"W":11.611161116111646;"S":-17.94743030603061;"E":24.068406840684105;"N":-4.453854347434742;"item":"Angola"};

如何做一个这样的选择按钮和系统从 WSEN_list 更新我的 WNES?


解决方案:this fiddle

【问题讨论】:

  • 没什么,我不知道该找什么。欢迎指征。
  • 你能改变数据结构,让它像`var locations = { "Afghanistan" : { "W": ....}, "India" : { "W" : . ..} };` 这意味着不循环对象,就像locations[text]
  • 您可以使用WSEN_list 中的位置索引作为每个选项的值。
  • 我已经用纯 js 为你实现了它,take a look here@LeGEC 给了我一个答案,所以我不会添加另一个 :)
  • 不,你需要像我上面使用的那样使用括号表示法。 WSEN_list[country_name]

标签: javascript jquery json forms


【解决方案1】:

您可能希望对 #mySelect 节点上的 change 事件做出反应:

$('#mySelect').change(function(){
    // this code will be executed each time the selection change

    // you can get the selected country like this :
    var country = this.value;

    // do whatever you want with this value
});

【讨论】:

  • 是的,我正在寻找类似的东西。
  • 您的系统 + @epascarello 数据结构更改听起来像是解决方案。
猜你喜欢
  • 2021-11-27
  • 1970-01-01
  • 2015-02-23
  • 2014-07-19
  • 1970-01-01
  • 2014-05-18
  • 2014-03-28
  • 2022-01-06
  • 2021-05-17
相关资源
最近更新 更多