在HTML中使用单个id名称的多个实例有什么副作用? [英] What are the side effects of using multiple instances of a single id name in HTML?

查看:97
本文介绍了在HTML中使用单个id名称的多个实例有什么副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在网页中使用相同的ID包含多个元素,只要好奇地找出究竟会导致我自己会出现什么问题?

例如: / p>

 < div id ='someID'>一些内容< / div> 
< div id ='someID'>一些其他内容< / div>


解决方案

当您尝试引用JavaScript中的元素时,不能解决你指的是哪一个元素。根据您运行的特定JavaScript解释器的不同,您可能会遇到错误或未定义的行为 - 这两种情况都是不可取的。



HTML规范指出Id应该是唯一的,所以你的HTML将被视为无效,并可能导致浏览器回退到怪异模式渲染,甚至完全拒绝渲染你的页面(虽然这不太可能,并且所有当前浏览器都会渲染一些东西 - 从技术上讲,如果你不按照规范浏览器没有义务做任何事情,但拒绝你的页面)。



如果您想通过以下方式标识多个元素,则应该考虑使用类名称:

 < div class =someClass>部分内容< / div> 
< div class =someClass>部分其他内容< / div>






Blair 在下面的评论中指出,如果你需要通过JavaScript从类中搜索元素,你可以通过从最近的元素一个ID,并告诉它要查找哪种节点类型。这可以在很多情况下快速保持访问速度,但不会违反任何重复ID的规则:

  HTML: 
< div id =myNearestID>
< div class =someClass>某些内容< / div>
< div class =someClass>部分其他内容< / div>
< / div>

JavaScript + JQuery:
$('#myNearestID div.someClass')


Just curious to find out exactly what problems I'll cause myself if I include multiple elements in my web-page with the same id?

for example:

<div id='someID'>Some Content</div>
<div id='someID'>Some Other Content</div>

解决方案

When you try and reference those elements from JavaScript it won't be able to resolve which element you are referring to. Depending on the specific JavaScript interpreter you are running on, you may either get errors, or undefined behaviour - both cases are undesirable.

The HTML spec states that Id's should be unique, so your HTML will be considered as invalid and may cause browsers to drop back into quirks mode rendering, or even totally refuse to render your page (although that's not likely, and all current browsers will render something - technically, if you don't follow the spec the browser is under no obligation to do anything but reject your page).

You should consider using class names instead if you want something to identify multiple elements by:

<div class="someClass">Some Content</div>
<div class="someClass">Some Other Content</div>


Blair has pointed out in the comments below that if you need to search for elements by class from JavaScript, you can speed the search up by going from the nearest element with an ID and also tell it what node type to look for. This can keep the access speed fast in a lot of cases, but doesn't break any rules on duplicate id's:

HTML:
<div id="myNearestID">
    <div class="someClass">Some Content</div>
    <div class="someClass">Some Other Content</div>
</div>

JavaScript+JQuery:
$('#myNearestID div.someClass')

这篇关于在HTML中使用单个id名称的多个实例有什么副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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