【问题标题】:Is there a way to get the next element in json when i have the previous index or id当我有前一个索引或 id 时,有没有办法在 json 中获取下一个元素
【发布时间】:2014-05-28 11:14:04
【问题描述】:

如果我有特定元素的键,有没有办法遍历 json 对象。

我的 json 在下面。如果我有一个键值 "1" ,我怎样才能在 json 对象中获取它的下一个值,即对应于键 **200** 的键值。

我不想使用 $.each,因为我必须在 onfinish 事件中遍历 json,所以我不能使用 $.each。任何帮助都会得到帮助

**The id will not always be sequential**

{ "root" : [ { "id" : "1",
        "trackUrl" : "http://player.vimeo.com/video/89996000?api=1&player_id=player1&autoplay=1"
      },
      { "id" : "200",
        "trackUrl" : "http://player.vimeo.com/video/17788981?api=1&player_id=player1&autoplay=1"
      },
      { "id" : "314",
        "trackUrl" : "http://player.vimeo.com/video/470742?api=1&player_id=player1&autoplay=1"
      }
    ] }

我想在下面的视频播放器 iam 构建的 onfinish 处理程序中遍历 json,基本上在 $(document).ready 函数中,我为我的视频播放器分配要播放的第一个 trackUrl。接下来,当视频播放完毕时,我想访问下一个 id = 200

的 trackurl
        function onFinish(id) {

            status.text('finished');
            Get next item in the Json object



        }

【问题讨论】:

  • 你想获取trackUrl属性的值对吧?
  • 但不想迭代root JSON 数组?
  • 是的,没错。因为我正在处理一个事件,所以我使用第一个值,在事件处理完成时我需要下一个值。
  • 我还是没有得到你的要求...
  • '在 json 对象中获取它的下一个值' -- 会一直是 'trackUrl' 吗?

标签: jquery json


【解决方案1】:

如果你有 Ids 序列号作为数组索引:0,1,2,3,4..... 你可以这样做:

var json= { "root" : [ { "id" : "0",
        "trackUrl" : "http://player.vimeo.com/video/89996000?api=1&player_id=player1&autoplay=1"
      },
      { "id" : "1",
        "trackUrl" : "http://player.vimeo.com/video/17788981?api=1&player_id=player1&autoplay=1"
      },
      { "id" : "2",
        "trackUrl" : "http://player.vimeo.com/video/470742?api=1&player_id=player1&autoplay=1"
      }
    ] };

var root = json.root, currentId=0;
alert(root[currentId+1].trackUrl);

我不确定这是否是您想要的,但您可以尝试一下或根据您的应用进行调整。

FIDDLE

更新: 我认为您必须像 photoViewer 应用程序一样跟踪 player 应用程序上的当前索引,因为您拥有当前索引,因为您拥有当前索引,因此您必须处理数组索引作为 id 值轻松下一个并更新您当前的索引持有者。

【讨论】:

  • 您好,非常感谢您的回复。它们不会一直是连续的,我以此为例。我已对问题进行了编辑。
  • 好的,可以加onfinish event handler吗,只是为了有使用的上下文
  • 等会儿肯定会补充的
  • 嗨票价,我已经添加了它
猜你喜欢
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
相关资源
最近更新 更多