Html duplicated ID

后端 未结 8 1773
渐次进展
渐次进展 2020-12-01 23:41

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 w

相关标签:
8条回答
  • 2020-12-02 00:10

    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

    0 讨论(0)
  • 2020-12-02 00:10

    I will suggest use class instead of id. Or add some postfix while generating dynamic ids.

    0 讨论(0)
  • 2020-12-02 00:20

    COMPONENTS: if you write reusable component e.g. ) in your example then if you put two ore more components into one document then you will get INVALID html. So instead id use class.

    0 讨论(0)
  • 2020-12-02 00:24

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

    0 讨论(0)
  • 2020-12-02 00:25

    Even though is is wrong there is nothing wrong with the selector in jQuery

    $('#Container1 #TextBox1').val(1)
    $('#Container2 #TextBox1').val(2)
    

    Demo: Fiddle


    A better choice will be use attribute selector

    $('#Container1 input[id="TextBox1"]').val(1)
    $('#Container2 input[id="TextBox1"]').val(2)
    

    Demo: Fiddle

    0 讨论(0)
  • 2020-12-02 00:31

    Depends on HTML version:

    1. HTML 4 ID must be document-wide unique.
    2. HTML 5 ID unique in there container tree.

    but we suggest are not good practice

    0 讨论(0)
提交回复
热议问题