下面是一个简化的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>`

我想获取每个AdaptationSet元素的Representation元素的codecs属性.

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');
})

密码运行得很好.但我认为这不是准确的解决方案,因为Representation个元素可能不止一个.所以我添加了一行代码(现在已被注释),但它不会起作用.有人能告诉我为什么吗?因为我在jQuery文档中看到过类似的例子,它是这样做的:

var item1 = $( "li.item-1" )[ 0 ];
$( "li.item-ii" ).find( item1 ).css( "background-color", "red" );

谢谢!

推荐答案

But I think this is not the accurate solution cause Representation element may be more than one.

您的代码很好,因为jQuery的.attr(attributeName)明确表示...

.attr()方法只获取匹配集中101个元素的属性值.

it's not gonna work. Can somebody tell me why?

通过[index]引用jQuery对象属性直接返回该元素.这相当于.get(index).在这种情况下,您需要使用本机DOM方法

$(audio).find('Representation')[0].getAttribute('codecs');

若要继续使用jQuery对象包装器,请改用.eq(index)

$(audio).find('Representation').eq(0).attr('codecs');

Javascript相关问答推荐

如何在不分配整个数组的情况下修改包含数组的行为主体?

如何在使用fast-xml-parser构建ML时包括属性值?

在Angular中将样式应用于innerHTML

Chrome是否忽略WebAuthentication userVerification设置?""

我可以从React中的出口从主布局调用一个处理程序函数吗?

Rehype将hashtag呈现为URL

加载背景图像时同步旋转不显示的问题

JS:XML insertBefore插入元素

JavaScript不重定向配置的PATH

如何在我的Next.js项目中.blob()我的图像文件?

如何限制显示在分页中的可见页面的数量

Reaction-SWR-无更新组件

在不扭曲纹理的情况下在顶点着色器中旋转UV

使用RxJS from Event和@ViewChild vs KeyUp事件和RxJS主题更改输入字段值

为什么我看到的是回复,而不是我的文档?

TypeORM QueryBuilder限制联接到一条记录

rxjs在每次迭代后更新数组的可观察值

是否有静态版本的`instanceof`?

如何使用useparams从react路由中提取id

Google OAuth 2.0库和跨域开放程序的问题-策略错误