通过JavaScript自动添加每个DIV的类(连续编号)? [英] adding classes (serially numbered) to each DIV on page automatically via javascript?

查看:179
本文介绍了通过JavaScript自动添加每个DIV的类(连续编号)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的wordpress安装中运行一个联系人表单插件。一切工作正常,但我想要更多地形式我的形式。像这样做,我必须以不同的方式来设计一些DIV(插件正在处理的)。问题是:所有DIV容器都没有ID或类!一切都由插件处理,我的PHP技能就像零,所以我必须处理这个裸体DIVs; - )



问题是:是否可能通过javascript向当前网站上的每个DIV添加连续编号的类别?



感谢目前为止,我希望你得到我的意思(对不起,那个shitty的英文)! / p>

解决方案

另一种方法是将回调传递给 .attr [docs]

  $('div')。attr('class',function(i){
return'someClass'+ i;
});

尽管您也可以使用ID作为ID,因为每个类都将是唯一的。



注意,您不必使用ID或类来选择元素,有一些选择器遍历方法,您可以获取对所需元素的引用。






防止覆盖现有类,或者只选择没有课程的元素,或以某种方式将 div s的选择缩小到只需要的元素:

  $('div:not([class])')

或使用 .addClass [docs] 而不是 .attr

  $('div')。addClass(function(i){
return'someClass'+ i;
});


i'm running a contact-form-plugin on my wordpress installation. everything works fine but i want to style my form a little bit more. to do it like this i have to style some DIVs (which the plugin is processing) in a different way. the problem is: all DIV-containers have no IDs or classes! everything is processed by the plugin and my PHP-skills are like zero so i have to deal with this "naked" DIVs ;-)

the question is: is it possible to add serially numbered classes to each DIV on the current site via javascript?

thanks so far and i hope you get waht i mean (sorry for that shitty english)!

解决方案

Yet another way, passing a callback to .attr [docs]:

$('div').attr('class', function(i) {
    return 'someClass' + i;
});

Though you could also use this for IDs instead, since each class will be unique.

Note that you don't have to use IDs or classes to select elements, there are a number of selectors and traversal methods with which you can get a reference to the elements you want.


To prevent overriding existing classes, either select only the elements with no class or somehow narrow down the selection of divs to only those you want:

$('div:not([class])')

or use .addClass [docs] instead of .attr:

$('div').addClass(function(i) {
    return 'someClass' + i;
});

这篇关于通过JavaScript自动添加每个DIV的类(连续编号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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