在同一个HTML文档中有多个相同的ID [英] Multiple identical IDs in the same HTML document

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

问题描述

我正在创建一个网页,其中包含可能包含ID的多个HTML模板。因此,最终的页面可能包含几个HTML元素具有完全相同的ID,这是不允许的

I am creating a web page that includes several HTML-templates that may contain IDs. As a result the final page may contain several HTML element with the exact same ID which is not allowed by HTML

仍然我似乎能够解决这个问题使用jQuery上下文,例如:$(#id54,template4),但是这将总是在所有浏览器中工作,或者一些浏览器会拒绝我多个ID?

Still I seem to be able to solve this problem using jQuery contexts, like: $( "#id54", template4 ), but will this always work in all browsers or will some browsers deny me multiple IDs?

推荐答案

$(selector,context)语法将始终只在给定上下文中进行搜索,因此只要您的ID在该上下文中是唯一的,

The $(selector, context) syntax will always only search within the given context, so as long as your ID's are unique within that context, your jQuery should work in all browsers.

正如你所意识到的,在模板中以这种方式使用ID是不明智的。

As you realize, though, it is ill-advised to use ID's in this manner, in templates.

由于不允许使用多个相同的ID,因此没有规定如何处理它们。它永远不能保证所有浏览器将继续支持你正在写的代码。

Since multiple identical ID's are not allowed, there is no specification for how they should be handled. It can never be guaranteed that all browsers will continue to support the code you're writing. That code will behave the way you expect on all major browsers today, though.

解决方法是在你的模板引擎中使用类或逻辑,以确保唯一的ID。 templateID-control-2-myButton

Workarounds would be using classes, or logic in your templating engine to ensure unique ID's, e.g. templateID-control-2-myButton.

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

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