Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - Html duplicated ID

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...