How can I apply a jQuery function to all elements with the same ID?

后端 未结 4 1935
旧时难觅i
旧时难觅i 2020-11-22 10:46

I am new to jQuery. I have the following code:

jQuery(document).ready(function() {
    jQuery(\'#carousel\').jcarousel();
});

It only appl

相关标签:
4条回答
  • 2020-11-22 11:14

    You can't have more than one element with the same Id, that's why is not working. You should use class="caroussel" instead.

    jQuery(document).ready(function() {
        jQuery('.carousel').jcarousel();
    });
    
    0 讨论(0)
  • 2020-11-22 11:15

    The IDs for elements are supposed to be unique in the DOM. Having the same ID for two or more elements is not valid html. To share functionality across elements, assign them a common class, rather than giving them the same ID. If you can't assign them a common class, the workaround below will allow you to select elements with the same id attribute:

    Using the same ID (If not possible to change ID)

    jQuery(document).ready(function() {
        jQuery('[id=carousel]').jcarousel();
    });
    

    Using a common class (Recommended way)

    jQuery(document).ready(function() { 
        jQuery('.carousel').jcarousel();
    });
    
    0 讨论(0)
  • 2020-11-22 11:19

    In this situation you should use class. You can not use id. Otherwise you can try the below code.

    jQuery('ul').jcarousel();
    
    0 讨论(0)
  • 2020-11-22 11:32

    In recent versions of jQuery, when you have multiple id's on the page, selector will return only the first 'id' that was found in the DOM. You should use class instead.

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