Access Multiple Elements of same ID in jQuery

前端 未结 4 697
离开以前
离开以前 2020-11-29 11:15

If i have elements such as this






        
相关标签:
4条回答
  • 2020-11-29 11:47

    Do not create markup that contains elements with duplicate IDs. This will break things, and you will be mauled by a velociraptor faster than you can say "goto".

    Use classes instead:

    <img src='0.jpg' id='images' />
    <img src='...' class='myEle' />
    <img src='...' class='myEle' />
    

    then...

    $(document).ready(function() {
        $('.myEle').live('mouseup', function () {
    
            $('#images').attr("src", myEle.getNumber() + ".jpg"); 
        });
    });
    

    Re: OP comment

    "How do i know which image is pressed?"

    Use the this keyword:

    $(document).ready(function() {
        $('.myEle').live('mouseup', function () {
    
            $('#images').attr("src", $(this).attr('src')); 
        });
    });
    

    ...I think that's what you're looking for.

    velociraptor

    0 讨论(0)
  • 2020-11-29 11:49

    If multiple elements will share a certain property, you should assign class to them instead of id. So the resulting jquery code will look something like:

    $('.myEle').mouseup();
    

    ID is to be used to uniquely identify elements.

    0 讨论(0)
  • 2020-11-29 12:04

    It is true that having multiple elements with the same id is incorrect. However it is pretty easy to generate such code in general-purpose frameworks, for example in Django one may have more than one forms in a single view with the same field auto_id. Thus it would be nice to have jQuery function which selects all of these elements so client-side Javascript code can check the length of returned list and trigger a client-side error / warning in such case.

    Also do not forget that the value of id has to be escaped in CSS query. While recent versions of Chrome / Firefox have native support of CSS.escape(), IE may require a polyfill: https://github.com/mathiasbynens/CSS.escape

    $.id = function(id) {
        // FF 54 generates warning when empty string is passed.
        if (typeof id !== 'string' || id === '') {
            return $();
        } else {
            // Support multiple ID's to detect content bugs.
            return $(document.querySelectorAll('#' + CSS.escape(id)))
        }
    };
    
    0 讨论(0)
  • 2020-11-29 12:09

    If you've inherited code so horrible that you can only work with the faulty output, use jQuery("[id=theidthatshouldbeaclassinstead]") or jQuery("[id*=theidthatshouldbeaclassinstead]") if there are multiple ids for some reason.

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