Html重复“id” [英] Html duplicated "id"

查看:159
本文介绍了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?

推荐答案

你绝对不应该有重复的身份证 。它可以工作*,但它在语义上是不正确的 你不应该这样做

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会接受选择器,但 NOT 是有利的,因为它不正确

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

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

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