简体   繁体   English

使用jquery动态添加css类

[英]Dynamically add css class with jquery

I'm trying to add a CSS class to an element with jQuery.我正在尝试使用 jQuery 向元素添加 CSS 类。 This class should be an increasing number.这个类应该是越来越多的。 For example, myclass_1 then the next is myclass_2 and so on.例如, myclass_1那么接下来是myclass_2等等。

It's easy to add an increasing number with a PHP while loop, but I don't know how can I apply PHP code inside of jQuery.使用 PHP while循环添加递增数字很容易,但我不知道如何在 jQuery 中应用 PHP 代码。 Or is there another way to do this?或者有另一种方法可以做到这一点?

jQuery('.myclass_').popup({ 
    //code
});

So, how can I add an increasing number after this .myclass_ ?那么,如何在.myclass_之后添加越来越多的数字?

Any suggestions please!请有任何建议!

Use a loop使用循环

var count = 5;

for(var i = 0; i < count; i++){
   jQuery('.myclass_'+i).popup({ 
       //code
   });
}

If you are using jQuery in your project then jQuery.each() API will ease your effort to get it done.如果您在项目中使用 jQuery,那么jQuery.each() API将减轻您完成它的工作。

Fiddle - http://jsfiddle.net/ylokesh/bwdq8t5r/小提琴- http://jsfiddle.net/ylokesh/bwdq8t5r/

One more suggestion, it would be good if you keep a generic class "myClass" on all nodes to be traversed and then append a new class with index number.还有一个建议,如果您在要遍历的所有节点上保留一个通用类“myClass”,然后附加一个带有索引号的新类,那就太好了。

JavaScript [using jQuery.each()] JavaScript [使用 jQuery.each()]

$('.myClass').each(function(index, element){
   $(element).addClass("myClass_" + index).text("Node " + index);
});

HTML HTML

<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM