jquery-selectors - 如何在JQuery中向同一个类添加不同的类?

标签 jquery-selectors addclass

我没有代码可以开始,因为我在 JQuery 方面并不先进,而这似乎是高级的东西。我知道如何添加类、隐藏元素和其他类型的东西,但这对我来说是新事物。问题就在这里。我有通过 php 和 mysql 提供的内容。所有内容都属于同一类别,并且每页列出五个。我需要为每个相同的类添加一个额外的类,以赋予它一个独特的类。下面是 html 的示例。

  <div id="1" class="example"></div>
  <div id="2" class="example"></div>
  <div id="3" class="example"></div>
  <div id="4" class="example"></div>
  <div id="5" class="example"></div>

我需要 Jquery 对 html 执行此操作:

  <div id="1" class="example ex1"></div>
  <div id="2" class="example ex2"></div>
  <div id="3" class="example ex3"></div>
  <div id="4" class="example ex4"></div>
  <div id="5" class="example ex5"></div>

为 Id 标记创建脚本是不切实际的,因为如果我有一千个 Id,那么我将不得不为每个 id 复制脚本一千次,并且随着列表变长,复制次数会更多。这仅用于 javascript 目的,因此我想将其保留在 javascript 中。如果有一种方法可以在服务器端完成此任务,我也会采纳这些建议。提前感谢大家为解决此问题提供的帮助。

最佳答案

现在我终于明白你想要什么了

需要此代码

// Wait on the document to be loaded
$(function(){
    // get every element with the class example in an array and loop
    // through it(each) with i  as index
    $(".example").each(function(i){
        // add class ex with the index
        // this is the element we are pointing at so a div
        $(this).addClass("ex" + i);
    });
});​

但是当您循环使用 5 个 div 的数组时,您可以在服务器端轻松完成此操作;)

关于jquery-selectors - 如何在JQuery中向同一个类添加不同的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12636348/

相关文章:

JQuery 通过 div ID 添加类/删除类

jquery - 使用悬停和添加/删除类问题

jquery - 如果父级有某个类,则将类添加到父级标记

javascript - 为什么点击复选框不添加选中的属性 ='checked'

jquery选择器: reference class inside of where i clicked:

jquery:无法获取div的 "value"属性

jquery - 无法通过 jquery 获取要切换/添加的类

jQuery - addClass 如果今天是今天

javascript - 通过 jquery 检查特定 <td> 中是否存在项目

javascript - 使用 jQuery 显示/隐藏基于复选框的 div