You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery find()获取MPD中Representation属性的问题求助

为什么$(audio).find('Representation')[0].attr('codecs')无法正常工作?

先看你提供的MPD XML结构:

const mpd = `<AdaptationSet id="1" lang="eng" mimeType="audio/mp4">
    <Representation codecs="mp4a.40.2" id="5" mimeType="audio/mp4"></Representation>
    <Representation codecs="mp4a.40.2" id="6" mimeType="audio/mp4"></Representation>
    <Representation codecs="mp4a.40.2" id="7" mimeType="audio/mp4"></Representation>
</AdaptationSet>
<AdaptationSet id="1" lang="eng" mimeType="audio/mp4">
    <Representation codecs="ec-3" id="8" mimeType="audio/mp4"></Representation>
</AdaptationSet>`

你的现有代码:

let mpdXML = $.parseXML(mpd);
let audios = $mpdXML.find("AdaptationSet[mimeType|='audio/mp4']");
$.each(audios, (id, audio) => {
    // let codecs = $(audio).find('Representation')[0].attr('codecs');
    let codecs = $(audio).find('Representation').attr('codecs');
})

问题核心原因

注释代码报错的本质是对象类型不匹配:

  • $(audio).find('Representation') 返回的是jQuery包装的元素集合
  • 用[0]取出的是集合中的第一个原生DOM元素,而原生DOM元素没有jQuery的.attr()方法——这个方法是jQuery对象专属的。

你看到的jQuery文档示例,是把原生DOM元素传给.find()作为参数,这是jQuery API允许的用法;但直接在DOM元素上调用.attr()属于方法调用对象错误,自然无法运行。

正确写法

如果要获取第一个Representation的codecs,有两种可行方式:

  1. 将原生DOM元素重新包装为jQuery对象:
let codecs = $( $(audio).find('Representation')[0] ).attr('codecs');
  1. 使用jQuery的.eq(0)方法直接获取第一个jQuery对象:
let codecs = $(audio).find('Representation').eq(0).attr('codecs');

如果要处理每个AdaptationSet下的所有Representation,应该遍历每个Representation元素:

$.each(audios, (id, audio) => {
    $(audio).find('Representation').each((idx, rep) => {
        let codec = $(rep).attr('codecs');
        // 这里处理每个codec值
        console.log(codec);
    });
})

内容的提问来源于stack exchange,提问作者hayley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 19:37:07