HTML重复ID [英] Html duplicated ID

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

问题描述

我的控件是根据用户输入动态构建的,还有n个文本框,其ID也是动态的.

My control is built dynamically accordingly to user input, there are n textboxes whose IDs are dynamic too.

但是,我没有预见到该HTML将在同一html页面中的其他地方重用.

However, I did not foresee that this HTML would be reused elsewhere within the same html page.

我现在面临的问题是重复的ID,这导致我的jQuery函数无法正常工作.

The problem I'm facing now are the duplicated IDs, which are causing my jQuery functions to not work well.

我确实知道ID应该是唯一的,但是,是否可以通过将最外面的<div>与不同的ID一起使用来避免此问题?

I do understand that IDs should be unique, however, can I avoid the issue by using the outermost <div> with different IDs?

任何专家都可以给我一些好的建议吗?

Any experts out there can give me some good advice?

P.S.我正在寻找一种有效的解决方案,因为如果需要更改每个元素的ID,则需要在jQuery中进行大量工作.

P.S. I'm looking for an effective solution, because if I need to change the ID for each element, it would require a lot of work in my jQuery.

请帮助.谢谢!

<div id="Container1">
  <div id="Control">
    <input type="text" id="TextBox1" />
    <input type="text" id="TextBox2" />
  </div>
</div>

<div id="Container2">
  <div id="Control">
    <input type="text" id="TextBox1" />
    <input type="text" id="TextBox2" />
  </div>
</div>

我想知道在jQuery函数中是否可以执行类似的操作.#container1 > #textbox1在选择区中?

I'm wondering if, in the jQuery functions, I can do something like.. #container1 > #textbox1 in the selection?

推荐答案

您绝对不应有重复的ID .可能有效*,但从语义上讲是不正确的, 您不应这样做

You absolutely should not have duplicate IDs. It may work*, but it is semantically incorrect and you should not do it

您应该重新构造jQuery,无论它有多臭.最好的选择是使用一个类,也许使用父级的特定ID来指定您想要的那个

You should restructure your jQuery, however much that may stink. The best option would be to use a class, perhaps using the specific id of the parent to specify which one you want

另一种较不吸引人但可行的方法是在ID的末尾添加一个数字或某些东西以使其唯一,然后使用jQuery来检测具有ID特定部分的任何元素

Another less attractive but viable way would be to add a number or something to the end of the ID to make it unique then use jQuery to detect any elements with a specific part of an ID

*-正如阿伦(Arun)所述,jQuery将接受选择器,但是有利的,因为它不正确

* - As Arun describes jQuery will accept the selector, but it is NOT favorable because it is incorrect

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

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