gpt4 book ai didi

jquery - 我如何访问这些属性?

转载 作者:行者123 更新时间:2023-12-01 08:19:27 25 4
gpt4 key购买 nike

我正疯狂地试图将这个 json 中每个“部门”的“name”和“id”属性解析为一个选择:

[{"division":{"name":"Solo Male","coed":false,"size":1,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":1}},{"division":{"name":"Solo Female","coed":false,"size":1,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":2}},{"division":{"name":"4 Person Male","coed":false,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":9}},{"division":{"name":"4 Person Female","coed":false,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":10}},{"division":{"name":"4 Person Coed","coed":true,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:28-04:00","id":11}},{"division":{"name":"3 Person Male","coed":false,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":6}},{"division":{"name":"3 Person Female","coed":false,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":7}},{"division":{"name":"3 Person Coed","coed":true,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:22-04:00","id":8}},{"division":{"name":"2 Person Male","coed":false,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":3}},{"division":{"name":"2 Person Female","coed":false,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":4}},{"division":{"name":"2 Person Coed","coed":true,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:16-04:00","id":5}}]

这是我无法运行的代码:

jQuery.each(data, function(i,division) {
$('#squad_division').append( $('<option value="'+ division.id+'">'+ division.name +'</option>'));

我知道我只是错过了一些简单的东西,我试图访问“division.id”和“division.name”,但它却让我困惑。

如果您能提供帮助,请先致谢。

干杯

最佳答案

由于 JSON 的结构,您需要将 division.id 更改为 division.division.id。这是您几乎完全相同的代码的jsfiddle,可以正常运行:http://jsfiddle.net/RqwBT/1/

基本上,您的 division 变量是数组(data 变量)内的一个键,该数组是一个对象,并且该对象有一个属性:division (其中包含您要访问的子属性)。

jQuery.each(data, function(i,division) {
$('#squad_division').append( '<option value="'+ division.division.id+'">'+ division.division.name +'</option>');
});

请注意,我删除了附加语句中 HTML 周围的 $(),因为它会产生不必要的开销。

我通过在每个函数中调用 console.log(division); 来解决这个问题,这允许我一次检查一个数组键,以了解如何访问对象的信息。这是我从新源加载 JSON 时的标准做法。

关于jquery - 我如何访问这些属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8188382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com