Html duplicated ID

2020-01-29 02:23发布

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

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

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

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. 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.

Please help. Thanks!

<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>

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

8条回答
家丑人穷心不美
2楼-- · 2020-01-29 02:58

I would suggest you to use class instead of id. Duplicate id's are not a good practice.

查看更多
欢心
3楼-- · 2020-01-29 02:58

You can't have the same id multiple times. Use class instead.

查看更多
登录 后发表回答