具有相同 ID 的多个元素 [英] Mulitple Elements with the same ID

查看:29
本文介绍了具有相同 ID 的多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在同一页面上使用相同 ID (#vid) 的三个视频上使用脚本.目前似乎只有一个视频可以使用该脚本.

I am trying to use a script on three videos using the same ID (#vid) on the same page. At the moment only one video seems to be able to use the script.

var video = document.getElementById('vid')
// When the 'ended' event fires
video.addEventListener('ended', function(){
  // Reset the video to 
  video.currentTime = 0;
  // And play again
  video.load();
});

推荐答案

大多数这些答案只是部分正确.

Most of these answers are only partially correct.

要使您的标记有效,id 必须是唯一的.但是,有时粗心的开发人员会在 DOM 中重复使用相同的 id.不要害怕,这不是世界末日,您仍然可以像使用类一样访问多个具有相同 ID 的元素.

For your markup to be valid, id's need to be be unique. However, sometimes careless developers re-use the same id in the DOM. Fear not, it isn't the end of the world, you can still access multiple elements with the same id as you might using classes.

document.querySelectorAll('#vid'); 

将返回具有相同 id 的元素的 HTMLCollection(类似数组的对象).

Will return a HTMLCollection (array like object) of elements with the same id.

这篇关于具有相同 ID 的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆