如何将 jQuery 函数应用于具有相同 ID 的所有元素? [英] How can I apply a jQuery function to all elements with the same ID?
问题描述
我是 jQuery 的新手.我有以下代码:
jQuery(document).ready(function() {jQuery('#carousel').jcarousel();});
它仅适用于带有 id="carousel"
的第一个 ul
,不适用于其他.如何将其应用于具有相同 ID 的所有元素?
HTML:
<div id="slideshow-carousel"><ul id="carousel" class="jcarousel jcarousel-skin-tango"><!-- ... -->
<!-- jQuery 不适用于此 div --><div id="slideshow-carousel"><ul id="carousel" class="jcarousel jcarousel-skin-tango"><!-- ... -->
元素的 ID 在 DOM
中应该是唯一.两个或多个元素具有相同 ID 是无效的 html.要跨元素共享功能,请为它们分配一个公共类,而不是给它们相同的 ID.如果您不能为它们分配一个公共类,下面的解决方法将允许您选择具有相同 id 属性的元素:
使用相同的 ID (如果无法更改 ID)
jQuery(document).ready(function() {jQuery('[id=carousel]').jcarousel();});
使用通用类(推荐方式)
jQuery(document).ready(function() {jQuery('.carousel').jcarousel();});
I am new to jQuery. I have the following code:
jQuery(document).ready(function() {
jQuery('#carousel').jcarousel();
});
It only applies to the first ul
with id="carousel"
, not for the others. How can I apply it to all elements which have the same ID?
HTML:
<!-- jQuery applies to this div -->
<div id="slideshow-carousel">
<ul id="carousel" class="jcarousel jcarousel-skin-tango">
<!-- ... -->
</ul>
</div>
<!-- jQuery does not apply for this div -->
<div id="slideshow-carousel">
<ul id="carousel" class="jcarousel jcarousel-skin-tango">
<!-- ... -->
</ul>
</div>
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();
});
这篇关于如何将 jQuery 函数应用于具有相同 ID 的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!