Can multiple different HTML elements have the same ID if they're different elements?

后端 未结 16 1915
无人及你
无人及你 2020-11-21 05:30

Can multiple HTML elements have the same ID if they\'re of different element types? Is a scenario like this valid? Eg:

div#foo
span#foo
a#foo
16条回答
  •  無奈伤痛
    2020-11-21 06:09

    Even if the elements are of different types it can cause you some serious problems...

    Suppose you have 3 buttons with the same id:

    
    
    
    

    Now you setup some jQuery code to do something when myid buttons are clicked:

    $(document).ready(function ()
    {
        $("#myid").click(function ()
        {
            var buttonData = $(this).data("mydata");
    
            // Call interesting function...
            interestingFunction();
    
            $('form').trigger('submit');
        });
    });
    

    What would you expect? That every button clicked would execute the click event handler setup with jQuery. Unfortunately it won't happen. ONLY the 1st button calls the click handler. The other 2 when clicked do nothing. It is as if they weren't buttons at all!

    So always assign different IDs to HTML elements. This will get you covered against strange things. :)

    
    
    
    

    Now if you want the click event handler to run when any of the buttons get clicked it will work perfectly if you change the selector in the jQuery code to use the CSS class applied to them like this:

    $(document).ready(function ()
    {
        $(".mybtn").click(function ()
        {
            var buttonData = $(this).data("mydata");
    
            // Call interesting function...
            interstingFunction();
    
            $('form').trigger('submit');
        });
    });
    

提交回复
热议问题