如何在JQuery中将不同的类添加到同一类? [英] How to add a different class to the same class in JQuery?

查看:161
本文介绍了如何在JQuery中将不同的类添加到同一类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有任何代码可以开始使用,因为我在JQuery方面并不先进,这在这里似乎是高级的东西.我知道如何添加类,隐藏元素和其他种类的东西,但这对我来说是新事物.这是问题所在.我有通过php和mysql提供服务的内容.内容将共享相同的类,并且每页列出五个.我需要每个相同的类都可以添加一个额外的类,以使其具有唯一性.下面是html外观的示例.

I have no code to start off with, because I'm not advanced in JQuery and this seems like advanced stuff here. I know how to add classes, hide elements and other sorts of things but this is a new thing for me here. Here's the problem. I have content being served via php and mysql. The content will all share the same class and will be listed five per page. I need to have each of the same classes to have an extra class added to them to give it a unique class. An example of what the html looks like is below.

  <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进行此操作:

I need Jquery to do this to the 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中.如果也有办法在服务器端完成此操作,我也会考虑这些建议.预先感谢大家对这个问题的任何帮助.

It will not be practical to create scripts for the Id tag, because if I have a thousand Id's, then I will have to replicate the script a thousand times per id and more so as the list gets longer. This is only for javascript purposes so I want to keep it within javascript. If there is a way to accomplish this on the server side as well I'll take those suggestions as well. Thanks to all in advance for any help with this problem.

推荐答案

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

Now I finnaly understand what you want

此代码是必需的

// 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遍历数组时,您可以在服务器端轻松做到这一点;)

but you could do this easily on server side when you loop through your array with 5 divs ;)

这篇关于如何在JQuery中将不同的类添加到同一类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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