0

在 javascript 中,我正在加载一个 json 对象,并尝试更新其中的值。html 中的元素具有与其路径相匹配的 id,例如,其中的“values.one”元素:

{"values":{"one":"val1","two":"val2"},"OtherStuff":"whatever"}

将与此元素有关:

<input id="values_one" type="text">val1</div>

当这个元素失去焦点时,我想获取“#values_one”的值(使用 jQuery)并设置使用我的 json 对象中的任何值。我已经想出了如何从现有的 json 对象中获取值(请参阅下面的可怕代码),但我最终只得到了值,因此设置它不会影响 json 对象。关于如何做到这一点的任何建议(假设我不知道失去焦点的元素是“values_one”、“values_two”还是可能映射到 json 对象的任何其他元素)?

这是我目前拥有的代码(不起作用),但很高兴将其废弃以获取实际有效的代码:

var saveEdit = function() {
  var data = getJson();
  pathElements = $(this).attr('id').split('_'); 
  length = pathElements.length;
  var path = data[pathElements[0]];
  index = 1;
  while (index < length) {
      path = path[pathElements[index]];
      length -= 1;
  }
  path = $(this).text(); //resets "path", but not data.values.one
  $(this).unbind();
}
4

2 回答 2

1

循环比长度短一个,以便获得包含与最后一个标识符匹配的属性的元素:

var path = data;
for (index = 0; index < length - 1; index++) {
  path = path[pathElements[index]];
}
path[pathElements[length - 1]] = $(this).text();
于 2013-03-17T01:01:11.277 回答
1

Firstly, there's no such thing as a "JSON Object". Yes, I'm being pedantic, but you should either have a "JSON String", or a "Javascript Object".

It looks like you're trying to modify a JSON string via events, instead of just having the object itself available to reference and modify. Why bother keeping it in a string? When you're ready to export the data (perhaps saving to a db), then just stringify(); the object and be on your way.

Take a look at the following jsFiddle for a working implementation that you can build off of: http://jsfiddle.net/julianlam/WRZPF/

于 2013-03-17T01:05:58.213 回答