[英]How can I apply a jQuery function to all elements with the same ID?
I am new to jQuery.我是 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.它仅适用于id="carousel"
的第一个ul
,不适用于其他 ul。 How can I apply it to all elements which have the same ID?如何将其应用于具有相同 ID 的所有元素?
HTML: 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>
You can't have more than one element with the same Id, that's why is not working.您不能拥有多个具有相同 ID 的元素,这就是为什么不起作用。 You should use class="caroussel"
instead.您应该改用class="caroussel"
。
jQuery(document).ready(function() {
jQuery('.carousel').jcarousel();
});
The IDs for elements are supposed to be unique in the DOM
.元素的 ID 在DOM
中应该是唯一的。 Having the same ID for two or more elements is not valid html .两个或多个元素的 ID 相同是无效的 html 。 To share functionality across elements, assign them a common class, rather than giving them the same ID.要跨元素共享功能,请为它们分配一个公共类,而不是给它们相同的 ID。 If you can't assign them a common class, the workaround below will allow you to select elements with the same id attribute:如果您不能为它们分配一个公共类,下面的解决方法将允许您选择具有相同 id 属性的元素:
Using the same ID (If not possible to change ID)使用相同的 ID (如果无法更改 ID)
jQuery(document).ready(function() {
jQuery('[id=carousel]').jcarousel();
});
Using a common class (Recommended way)使用通用类(推荐方式)
jQuery(document).ready(function() {
jQuery('.carousel').jcarousel();
});
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.在最新版本的 jQuery 中,当页面上有多个 id 时,选择器将仅返回在 DOM 中找到的第一个“id”。 You should use class instead.您应该改用类。
In this situation you should use class.在这种情况下,您应该使用类。 You can not use id.你不能使用id。 Otherwise you can try the below code.否则你可以试试下面的代码。
jQuery('ul').jcarousel();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.