如何将jQuery函数应用于具有相同ID的所有元素? [英] How can I apply a jQuery function to all elements with the same ID?

查看:74
本文介绍了如何将jQuery函数应用于具有相同ID的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jQuery的新手。我有以下代码:

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

它仅适用于第一个 ul with id =carousel,而不是其他的。如何将其应用于所有具有相同ID的元素?



HTML:

 <! -  jQuery适用于这个div  - > 
< div id =slideshow-carousel>
< ul id =carouselclass =jcarousel jcarousel-skin-tango>
<! - ... - >
< / ul>
< / div>

<! - jQuery不适用于此div - >
< div id =slideshow-carousel>
< ul id =carouselclass =jcarousel jcarousel-skin-tango>
<! - ... - >
< / ul>
< / div>


解决方案

元素的ID应该是 DOM 中的唯一。对于两个或更多元素具有相同的ID是不正确的HTML 。要跨元素共享功能,请为其分配一个通用类,而不是给它们相同的ID。如果您无法为其分配普通类,下面的解决方法将允许您选择具有相同id属性的元素:



使用相同的ID (If不能更改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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆